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 to share
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 to share