PHP在字符串中组合两个最接近的单词


PHP combining two nearest words in a string

我需要php代码在字符串

中组合两个最接近的单词

eg: "我需要再短一点"

我需要,需要,变得,更短,更短,为了,当然,当然,通过,通过,很多

任何想法?真的不知道怎么处理

由于您是新手,我将为您创建一些代码,但从现在开始您应该先自己尝试。

function pairwise_sentence($sentence)
{
    $pairs = array();
    $words = explode(' ', $sentence);
    for($i = 1; $i < sizeof($words); $i++)
        $pairs[] = $words[$i - 1] . ' ' . $words[$i];
    return implode(',', $pairs);
}

这将生成您所描述的内容。如果您需要一个包含单词对的数组,则可以删除implode函数并只返回对。

<?php
$string = "I need to be shorter for sure by a lot";
$words = explode(" ", $string);
$loop_count = count($words) - 1;
for ($i=0; i<$loop_count; $i++) {
    // compare $words[$i] and $words[$i+1]
}
?>