PHP:将句子的单词组合成具有固定数量单词的较小组

时间:2018-04-29 08:25:02

标签: php arrays string split

我有这样的句子:

I am in love with you

我希望从左到右依次为3个单词组合。

I am in
am in love
in love with
love with you

我尝试了下面的代码,但我认为我让它复杂化了......

$data = array_chunk(explode(" ", $sarr), 3);
$data = array_map(function($value) {
    return sprintf("<span>%s</span>", implode(" ", $value));
}, $data);
echo implode("\n", $data);

有关如何快速有效地完成任务的任何想法?这必须适用于5000字。

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式解决此问题。您匹配一个单词,然后使用正向前瞻捕获另外两个单词,并将它们粘贴在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];
}

输出(print_r($words);):

Array
(
    [0] => I am in
    [1] => am in love
    [2] => in love with
    [3] => love with you
)

echo implode(PHP_EOL, $words);的输出:

I am in
am in love
in love with
love with you

答案 1 :(得分:1)

你肯定是一个强大的开始,但你想在你的阵列上滚动窗口。你可以这样做:

// 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);