如何将字符串分割成单词对?

3

我可以帮你将一个字符串在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);

有没有一种简单的方法可以将字符串分成单词对,但不重复单词?谢谢。


2
正则表达式并不总是解决“字符串”的答案。 - Incognito
4个回答

9
为什么不直接使用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


如何将 split this, string 分割? - user187291
1
@stereofrog,也许可以使用preg_split()函数来按\W或类似字符进行分割。 - Fanis Hatzidakis
我在你的解决方案中的for循环后添加了if ((count($arr) % 2) != 0) { $result[] = $arr[count($arr) - 1]; }来获取最后一个单词,它非常有效,谢谢。 - John Scipione

2

如果您想使用正则表达式进行重复匹配,您需要一些前瞻或后顾。否则,表达式将无法多次匹配相同的单词:

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

请注意,它不会像您请求的那样重复上一个单词“please”,尽管我不确定为什么您希望出现这种行为。

1
你可以使用 explode 函数将字符串分割成数组,然后遍历它:
$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];
}

我认为这个方法可行,但应该有更简单的解决方案。
根据codaddict的要求进行编辑。

你的输出与 OP 的要求不匹配。 - codaddict
哇,你说得对,codaddict。我其实还在想你的答案是错的,讽刺的是。 - jps
使用$j是完全多余的。 - Lightness Races in Orbit

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接