Php 如何将字符串拆分为单词对?

Php 如何将字符串拆分为单词对?,php,regex,arrays,string,Php,Regex,Arrays,String,我试图在PHP中将字符串拆分为一个单词对数组。例如,如果您有输入字符串: "split this string into word pairs please" 输出数组应该如下所示 Array ( [0] => split this [1] => this string [2] => string into [3] => into word [4] => word pairs [5] => pairs plea

我试图在PHP中将字符串拆分为一个单词对数组。例如,如果您有输入字符串:

"split this string into word pairs please"
输出数组应该如下所示

Array (
    [0] => split this
    [1] => this string
    [2] => string into
    [3] => into word
    [4] => word pairs
    [5] => pairs please
    [6] => please
)
一些失败的尝试包括:

$array = preg_split('/\w+\s+\w+/', $string);
这给了我一个空数组

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

它将字符串拆分为单词对,但不重复单词。有没有一个简单的方法可以做到这一点?谢谢。

为什么不直接使用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];
$str=“请将此字符串拆分为单词对”;
$arr=爆炸(“”,$str);
$result=array();

对于($i=0;$i您可以
分解
字符串,然后在其中循环:

$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];
}
$str=“请将此字符串拆分为单词对”;
$strSplit=爆炸(“”,$str);
$final=array();

对于($i=0,$j=0;$i如果要使用正则表达式重复,则需要某种形式的向前或向后查找。否则,表达式将无法多次匹配同一个单词:

$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);
输出:

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"
}
请注意,它并没有按照您的要求重复最后一个单词“请”,尽管我不确定您为什么想要这种行为

$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);
给出:

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

如果((count($arr)%2)!=0){$result[]=$arr[count($arr)-1];,那么
拆分这个字符串怎么样?@stereofrog,也许
preg_split()
要在
\W
上拆分呢
在解决方案中的for循环之后,抓住最后一个单词,效果很好,谢谢。您的输出不符合OP的要求。哇,您的正确的codaddicient,讽刺的是,我实际上认为您的答案是错误的。
$j
的使用完全是多余的。regex并不总是“字符串”的答案