PHP删除数组中的重复单词

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (46)

对不起,英语不是我的母语,也许题目不是很好。我想做这样的事。

$str = array("Lincoln Crown","Crown Court","go holiday","house fire","John Hinton","Hinton Jailed");

这是一个数组,“林肯皇冠”包含“林肯”和“皇冠”,因此删除下一个单词,其中包含这两个词,“皇宫(包含皇冠)”已被删除。

in another case. "John Hinton" contain "John" and "Hinton", so "Hinton Jailed(contain Hinton)" has been removed. the final output should be like this:

$output = array("Lincoln Crown","go holiday","house fire","John Hinton");

for my php skill is not good, it is not simply to use array_unique() array_diff(), so open a question for help, thanks.

提问于
用户回答回答于

我认为这可能有用:P

function cool_function($strs){
    // Black list
    $toExclude = array();

    foreach($strs as $s){
        // If it's not on blacklist, then search for it
        if(!in_array($s, $toExclude)){
            // Explode into blocks
            foreach(explode(" ",$s) as $block){
                // Search the block on array
                $found = preg_grep("/" . preg_quote($block) . "/", $strs);
                foreach($found as $k => $f){
                    if($f != $s){
                        // Place each found item that's different from current item into blacklist
                        $toExclude[$k] = $f;
                    }
                }
            }
        }
    }

    // Unset all keys that was found
    foreach($toExclude as $k => $v){
        unset($strs[$k]);
    }

    // Return the result
    return $strs;
}

$strs = array("Lincoln Crown","Crown Court","go holiday","house fire","John Hinton","Hinton Jailed");
print_r(cool_function($strs));

垃圾场:

Array
(
    [0] => Lincoln Crown
    [2] => go holiday
    [3] => house fire
    [4] => John Hinton
)
用户回答回答于

正如我在你的情况下所做的那样:

$words = array();

foreach($str as $key =>$entry)
{
   $entryWords = explode(' ', $entry);
   $isDuplicated = false;
   foreach($entryWords as $word)
        if(in_array($word, $words))
            $isDuplicated = true;
   if(!$isDuplicated)
        $words = array_merge($words, $entryWords);
   else
        unset($str[$key]);
}

var_dump($str);

输出:

array (size=4)
  0 => string 'Lincoln Crown' (length=13)
  2 => string 'go holiday' (length=10)
  3 => string 'house fire' (length=10)
  4 => string 'John Hinton' (length=11)

扫码关注云+社区

领取腾讯云代金券