PHP删除数组中的重复单词 [英] php remove duplicate words in an array
问题描述
对不起,英语不是我的母语,也许标题不太好.我想做这样的事情.
Sorry for English is not my mother language, maybe the question title is not quite good. I want to do something like this.
$str = array("Lincoln Crown","Crown Court","go holiday","house fire","John Hinton","Hinton Jailed");
这是一个数组,"Lincoln Crown"包含"Lincoln"和"Crown",因此删除包含这2个单词的下一个单词,并且"Crown Court(包含Crown)"已被删除.
here is an array, "Lincoln Crown" contain "Lincoln" and "Crown", so remove next words, which contains these 2 words, and "Crown Court(contain Crown)" has been removed.
在另一种情况下."John Hinton"包含"John"和"Hinton",因此已删除"Hinton Jailed(包含Hinton)".最终输出应如下所示:
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");
因为我的php技能不好,不能简单地使用array_unique()array_diff(),所以请提出一个帮助的问题,谢谢.
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
I think this might work :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
)
这篇关于PHP删除数组中的重复单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!