tags:

views:

522

answers:

5

Duplicate: http://stackoverflow.com/questions/840807/wondering-how-to-do-php-explode-over-every-other-word

$string = "This is my test case for an example."

If I do explode based on ' ' I get an

Array('This','is','my','test','case','for','an','example.');

What I want is an explode for every other space.

I'm looking for the following output:

Array( 

[0] => Array ( 

[0] => This is
[1] => is my
[2] => my test
[3] => test case 
[4] => case for 
[5] => for example. 

)

so basically every 2 worded phrases is outputted.

Anyone know a solution????

A: 

Two quick options come to mind: explode by every word and reassemble in pairs, use a regular expression to split the string instead of explode().

acrosman
But it's not at all easy to find a regexp that will do it. I think the explode-and-then-pair solultion is the way to go.
Colin Fine
A: 
$arr = explode($string);
$arr2 = array();
for ( $i=0; $i<size($arr)-1; $i+=2 ) {
    $arr2[] = $arr[i].' '.$arr[i+1];
}
if ( size($arr)%2==1 ) {
    $arr2[] = $arr[size($arr)-1];
}

$arr2 is the solution.

zilupe
+2  A: 

this will provide the output you're looking for

$string = "This is my test case for an example.";
$tmp = explode(' ', $string);
$result = array();
//assuming $string contains more than one word
for ($i = 0; $i < count($tmp) - 1; ++$i) {
    $result[$i] = $tmp[$i].' '.$tmp[$i + 1];
}
print_r($result);
Sylvain
thank you sylviain, this was most helpful. Im no php guru and took me a few reads to get my head around your code but now I get it =) I even got it to work for every 3 words which was my next challenge. thanks again
First Found
take a look at a solution without counting/indexing, too (using 'chasing pointers'), at http://stackoverflow.com/questions/857441/php-explode-over-every-other-word-with-a-twist/858073#858073
xtofl
+2  A: 

An alternative, making use of 'chasing pointers', would be this snippet.

$arr = explode( " ", "This is an example" );
$result = array();

$previous = $arr[0];
array_shift( $arr );
foreach( $arr as $current ) {
    $result[]=$previous." ".$current;
    $previous = $current;
}

echo implode( "\n", $result );

It's always fun to not need indices and counts but leave all these internal representational stuff to the foreach method (or array_map, or the like).

xtofl
+2  A: 

A short solution without loops (and a variable word count):

    function splitStrByWords($sentence, $wordCount=2) {
        $words = array_chunk(explode(' ', $sentence), $wordCount);
        return array_map('implode', $words, array_fill(0, sizeof($words), ' '));
    }
Artem Nezvigin