views:

107

answers:

4

I am trying to split a string into an array of word pairs in PHP. So for example if you have the input string:

"split this string into word pairs please"

the output array should look like

Array (
    [0] => split this
    [1] => this string
    [2] => string into
    [3] => into word
    [4] => word pairs
    [5] => pairs please
    [6] => please
)

some failed attempts include:

$array = preg_split('/\w+\s+\w+/', $string);

which gives me an empty array, and

preg_match('/\w+\s+\w+/', $string, $array);

which splits the string into word pairs but doesn't repeat the word. Is there an easy way to do this? Thanks.

+4  A: 

Why not just use explode ?

$str = "split this string into word pairs please";

$arr = explode(' ',$str);
$result = array();
for($i=0;$i<count($arr)-1;$i++) {
        $result[] =  $arr[$i].' '.$arr[$i+1];
}
$result[] =  $arr[$i];

Working link

codaddict
how about `split this, string` ?
stereofrog
@stereofrog, perhaps `preg_split()` to split on `\W` or similar
Fanis
I added `if ((count($arr) % 2) != 0) { $result[] = $arr[count($arr) - 1]; }` after the for loop in your solution to grab the last word and it worked great, thanks.
John Scipione
+1  A: 

You could explode the string and then loop through it:

$str = "split this string into word pairs please";
$strSplit = explode(' ', $str);
$final = array();    

for($i=0, $j=0; $i<count($strSplit); $i++, $j++)
{
    $final[$j] = $strSplit[$i] . ' ' . $strSplit[$i+1];
}

I think this works, but there should be a way easier solution.

Edited to make it conform to OP's spec. - as per codaddict

Jud Stephenson
your output does not match OP's requirement.
codaddict
Wow, your right codaddict, and I was actually thinking your answer was wrong, ironically.
Jud Stephenson
+1  A: 

If you want to repeat with a regular expression, you'll need some sort of look-ahead or look-behind. Otherwise, the expression will not match the same word multiple times:

$s = "split this string into word pairs please";
preg_match_all('/(\w+) (?=(\w+))/', $s, $matches, PREG_SET_ORDER);
$a = array_map(
  function($a)
  {
    return $a[1].' '.$a[2];
  },
  $matches
);
var_dump($a);

Output:

array(6) {
  [0]=>
  string(10) "split this"
  [1]=>
  string(11) "this string"
  [2]=>
  string(11) "string into"
  [3]=>
  string(9) "into word"
  [4]=>
  string(10) "word pairs"
  [5]=>
  string(12) "pairs please"
}

Note that it does not repeat the last word "please" as you requested, although I'm not sure why you would want that behavior.

konforce
+1  A: 
$s = "split this string into word pairs please";

$b1 = $b2 = explode(' ', $s);
array_shift($b2);
$r = array_map(function($a, $b) { return "$a $b"; }, $b1, $b2);

print_r($r);

gives:

Array
(
    [0] => split this
    [1] => this string
    [2] => string into
    [3] => into word
    [4] => word pairs
    [5] => pairs please
    [6] => please
)
Scott Evernden