PHP exploded over any other word with a twist?

Duplicate: Expand all other words

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

      

If I explode based on ' '

I get

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

      

I want to explode for any other space.

I am 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 2 expressed phrases are displayed.

Does anyone know a solution ????

+1


a source to share


6 answers


this will provide the output you are 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);

      



Wrapped in a function:

function splitWords($text, $cnt = 2) 
{
    $words = explode(' ', $text);

    $result = array();

    $icnt = count($words) - ($cnt-1);

    for ($i = 0; $i < $icnt; $i++)
    {
        $str = '';

        for ($o = 0; $o < $cnt; $o++)
        {
            $str .= $words[$i + $o] . ' ';
        }

        array_push($result, trim($str));
    }

    return $result;
}

      

+3


a source


An alternative using "hunting 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 a good idea not to index and count, but to leave all this internal representational stuff to the foreach (or array_map or the like) method.

+2


a source


Short solution without loops (and number of variables):

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

      

+1


a source


Two quick options come to mind: explode with every word and assemble in pairs, use regex to split the string instead of explode ().

0


a source


$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.

0


a source


  $content="This is my test case for an example";
  $tmp=explode(" ",$content);
  $text = array();
  $b=0;
  for ($i = 0; $i < count($tmp)/2; $i++) {
      $text[$i] = $tmp[$b].' '.$tmp[$b + 1];
      $b++;
  $b++;
  }
  print_r($text);

      

0


a source







All Articles