68

可能重复:
如果它存在于“不允许的单词”数组中,则从数组中删除它

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

$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从中选择一组随机的单词。我已经尝试了很多事情来达到我的结果,但到目前为止还没有。有人可以帮我解决这个问题吗?

4

2 回答 2

95

您正在寻找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);

看到它在行动

于 2012-05-14T19:40:30.347 回答
47

听起来很容易array_diff()

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

比较array1array2返回差异。

这基本上意味着它会array1在它被剥夺所有存在于array2.

于 2012-05-14T19:40:37.573 回答