抱歉,英语不是我的母语,也许问题标题不太好。我想做这样的事情。
$str = array("Lincoln Crown","Crown Court","go holiday","house fire","John Hinton","Hinton Jailed");
这里是一个数组,“Lincoln Crown”包含“Lincoln”和“Crown”,因此删除下一个包含这2个单词的单词,并且“Crown Court(contain Crown)”已被删除。
在另一种情况下。 “John Hinton”包含“John”和“Hinton”,因此“Hinton Jailed(包含 Hinton)”已被删除。最终的输出应该是这样的:
$output = array("Lincoln Crown","go holiday","house fire","John Hinton");
由于我的php技术不好,不能简单地使用array_unique() array_diff(),所以提出问题寻求帮助,谢谢。
最佳答案
我认为这可能有用: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删除数组中重复的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16221657/