用PHP中的句子删除数组中的重复单词

预编程777

我有一个包含单词和句子的字符串数组。

例如:

array("dog","cat","the dog is running","some other text","some","text")

我想删除重复的单词,只留下唯一的单词。即使在句子中,我也想删除这些词。

结果应如下所示:

array("dog","cat","the is running","other","some","text")

我尝试了该array_unique功能,但没有用。

温德

您可以使用array_unique带有爆炸和after 循环array_push

$res = [];
foreach($arr as $e) {
    array_push($res, ...explode(" ", $e));
}
print_r(array_unique($res));

参考:array_pushexplodearray-unique

现场示例:3v4l

如果你想保留句子使用:

$arr = array("dog","cat","the dog is running","some other text","some","text");

// sort first to get the shortest sentence first
usort($arr, function ($a, $b) {return count(explode(" ", $a)) - count(explode(" ", $b)); });

$words = [];
foreach($arr as &$e) {
    $res[] = trim(strtr($e, $words)); //get the word after swapping existing
    foreach(explode(" ", $e) as $w)
        $words[$w] =''; //add all new words to the swapping array with value of empty string
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章