如何在php中删除字符串中重复的单词

时间:2016-02-04 12:03:36

标签: php

我有一个包含许多单词的字符串,例如:

$str = "FileZilla Portable FileZilla 3.9
        FileZilla Portable Additional Versions
        7-Zip Portable 7-Zip Portable 4.42";

我想删除所有dupplicates并仅返回每个单词一次:

$str = "FileZilla Portable 3.9
        FileZilla Portable Additional Versions
        7-Zip Portable 4.42";

我怎么能用php做到这一点?

2 个答案:

答案 0 :(得分:4)

这样做:

$str = "FileZilla Portable FileZilla 3.9
        FileZilla Portable Additional Versions
        7-Zip Portable 7-Zip Portable 4.42";

$arr = array_unique(explode("\n", $str));
$arrLength = count($arr);
for($i = 0; $i < $arrLength; ++$i){
    $arr[$i] = implode(" ", array_unique(explode(" ", $arr[$i])));
}
$str = implode("\n", $arr);

echo $str;

以下是相关参考资料:

答案 1 :(得分:0)

这是我的代码。

$str = "FileZilla Portable FileZilla 3.9 FileZilla Portable Additional Versions 7Zip Portable 7Zip Portable 4.42";

$arr = explode("\n", $str);
foreach($arr as $st) {
   echo implode(" ", array_unique(explode(" ", $st)));
}

但数字(7Zip)没有删除...