1
$str =  "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";
$pieces = explode(" ",$str, 3);

print_r($pieces);

This gives me:

$pieces[0] = 'Hello';
$pieces[1] = 'fri3nd,';
$pieces[2] = 'you\'re looking good today!  What a Great day this is!  How     fancy and cool!';

How can I explode into every 3 or 4 words?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
ionfish
  • 151
  • 1
  • 4
  • 9
  • 4
    In your title, you are asking about equal portions, in the question, you ask about every 3 or 4 words. Which one is it and how do you want it to work exactly? – Pekka May 30 '11 at 07:06
  • Can u explain a bit more about your requirement and situation? Why do u want to split by 3 or 4 words? if u can explain your requirement, we may point a best solution. – Vijay May 30 '11 at 07:16
  • Possible duplicate of http://stackoverflow.com/questions/857441/php-explode-over-every-other-word-with-a-twist and http://stackoverflow.com/questions/840807/wondering-how-to-do-php-explode-over-every-other-word – Till May 30 '11 at 07:19
  • You can also try [`preg_match_all('~(?:\S+\s*){1,3}(?<!\s)~', $str, $out)`](https://tio.run/##FY49C8IwGIT3/IorCEm0g@LmBx3tWHBwsFJCP4Mxb0lSpIj@9dre8Bw8t1zf9dN0SrI0Y2zlg8MZPK2NITRO720VY6Qh566GIXpq26IlqhCoUmME3DoVoHBx9dyzQui0h/bzlNIbSxplyxHKViiJTMSPjOlG9K5ui5cKZVcoYwT/ieSQXze5X8vPLt5/RXKKci9/PMZyayYNQUp8GNA7bUPhxKLu24c8su80/QE) though the idea from @mickmackusa is very nice and possible more efficient! – bobble bubble May 19 '23 at 17:01

3 Answers3

2

Maybe:?

<?php
$str =  "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";

$array = array_map(create_function('$a', 'return implode(" ", $a);'), array_chunk(preg_split('/\s+/', $str), 3));
var_dump($array);

Explanation:

  • first you split the string at any (combined) whitespace: preg_split
  • then 'split' the resulting array: array_chunk
  • you then apply implode using array_map on any resulting group of words
Yoshi
  • 54,081
  • 14
  • 89
  • 103
1

Make 3 or 4 repetitions of a regex pattern that matches one or more visible characters followed by one or more whitespace characters.

This will produce strings of three/four words, with the exception of the last element which may have less than three/four words depending on the total word count.

Code: (Demo)

$str = "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";

var_export(
    preg_split('/(?:\S+\K +){3}/', $str)
);

This is an adjustment of this answer which doesn't need to accommodate multiple spaces.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

Use the php str_split function:-

$pieces = str_split( $str, 3);
Samuel Katz
  • 24,066
  • 8
  • 71
  • 57
  • 1
    that doesnt split according to words. it just smashes the whole thing into pieces. explode splits by words, but I'm not able to choose the way it's "exploding" them apart. – ionfish May 30 '11 at 07:10