PHP:将一个句子中的单词按固定的单词数分组

PHP:将一个句子中的单词按固定的单词数分组,php,arrays,string,split,Php,Arrays,String,Split,我有这样一句话: 我爱上你了 我希望这是在以下三个字从左到右的组合 我在 我恋爱了 爱上 爱你 我尝试了下面的代码,但我想我把它复杂化了 $data = array_chunk(explode(" ", $sarr), 3); $data = array_map(function($value) { return sprintf("<span>%s</span>", implode(" ", $value)); }, $data); echo implode(

我有这样一句话:

我爱上你了
我希望这是在以下三个字从左到右的组合

我在
我恋爱了
爱上
爱你
我尝试了下面的代码,但我想我把它复杂化了

$data = array_chunk(explode(" ", $sarr), 3);
$data = array_map(function($value) {
    return sprintf("<span>%s</span>", implode(" ", $value));
}, $data);
echo implode("\n", $data);
$data=array\u块(explode(“,$sarr),3);
$data=数组\映射(函数($value){
返回sprintf(“%s”,内爆(“,$value));
}美元数据);
回波内爆(“\n”,$data);

关于如何快速有效地完成这项工作,有什么想法吗?这必须适用于5000个单词。

您可以使用正则表达式来解决这一问题。你匹配一个单词,然后用积极的前瞻性捕捉下面的两个单词,并将它们粘在一个
foreach
循环中

$words = [];
preg_match_all('~\b\w+(?=((?:\s+\w+){2}))~', $str, $matches);
foreach ($matches[0] as $key => $word) {
    // 1st iteration => $word = "I", $matches[1][0] = " am in"
    $words[] = $word . $matches[1][$key];
}
输出(
打印($words);
):

回波内爆的输出(PHP_EOL,$words)


您肯定有一个良好的开端,但您希望在阵列上有一个滚动窗口。你可以这样做:

// split the string into words
$words = explode(" ", $sarr);
// for each index in the array, get that word and the two after it
$chunks = array_map(function($i) use ($words) {
    return implode(" ", array_slice($words,$i,3));
}, array_keys($words));
// cut off the last two (incomplete) chunks
$chunks = array_slice($chunks,0,-2);
// glue the result together
echo implode("\n",$chunks);

你已经准备好了。“拆分成单词,将单词分成3组,将每组重新连接在一起”。。。我真的找不到更好的方法了。但是我只得到了两套我喜欢的&哦,我明白了,你想要一种滚动的3字分组。好的,这有点棘手,但是你可以做的是
分解
,然后
映射
每个单词到
切片
,从其索引开始,然后拉入接下来的两个单词<代码>切片最后两个条目,就这样。有趣的是,regex解决方案在
n上的速度快了10倍≃ 6500
I am in
am in love
in love with
love with you
// split the string into words
$words = explode(" ", $sarr);
// for each index in the array, get that word and the two after it
$chunks = array_map(function($i) use ($words) {
    return implode(" ", array_slice($words,$i,3));
}, array_keys($words));
// cut off the last two (incomplete) chunks
$chunks = array_slice($chunks,0,-2);
// glue the result together
echo implode("\n",$chunks);