如果在另一个数组中找到它,则删除它们的元素

时间:2012-05-14 19:36:43

标签: php arrays

  

可能重复:
  Remove item from array if it exists in a 'disallowed words' array

我有一个客户端将发送的动态字符串,我想从中创建逗号分隔的标签:

$subject = "Warmly little in before cousin as sussex and an entire set Blessing it ladyship.";
print_r($tags = explode(" ", strtolower($subject)));

然而,我想删除一组特定的单词(例如明确的文章),但我想删除该单词的键和值(如果它在爆炸数组中):

$definite_articles = array('the','this','then','there','from','for','to','as','and','or','is','was','be','can','could','would','isn\'t','wasn\'t', 'until','should','give','has','have','are','some','it','in','if','so','of','on','at','an','who','what','when','where','why','we','been','maybe','further');

如果$definite_article数组中的其中一个单词位于$tags数组中,则删除该单词的键和值,新数组将取出这些单词。我将array_rand使用此数组来从中选择一组随机单词。我已经尝试了很多东西来实现我的结果,但到目前为止还没有。有人可以帮我找到解决方法吗?

2 个答案:

答案 0 :(得分:70)

您正在寻找array_diff

$subject = "Warmly little in before cousin as sussex...";
$tags = explode(" ", strtolower($subject));

$definite_articles = array('the','this','then','there','from','for','to','as');

$tags = array_diff($tags, $definite_articles);
print_r($tags);

<强> See it in action

答案 1 :(得分:33)

array_diff()听起来很容易。

array array_diff ( array $array1 , array $array2 [, array $... ] )
     

array1array2进行比较并返回差异。

这基本上意味着在array1中删除array2中存在的所有值后,它将返回{{1}}。