How do you break a string into word pairs?

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

"split this string into word pairs please"

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 unsuccessful attempts include:

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

which gives me an empty array, and

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

which breaks the string into pairs of words but does not repeat the word. Is there an easy way to do this? Thank.

+3
source share
4 answers

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

+9
source

If you want to repeat with regular expression, you will need some kind of look or look. Otherwise, the expression will not coincide with the same word several 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);

Conclusion:

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"
}

, "", , , .

+2

You can explodeline up and then scroll 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 simplified solution.

Edited to match OP specification. - according to codaddict

+1
source
$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
)
+1
source

Source: https://habr.com/ru/post/1768491/


All Articles