检查数组包含有另一个数组元素的元素 [英] Check if array contains elements having elements of another array
问题描述
$find=array('or','and','not');
$text=array('jasvjasvor','asmasnand','tekjbdkcjbdsnot');
我要检查,如果文本数组包含任何元素找到了。我能为单一的文本做到这一点,但不知道如何做到这一点的所有文字
I have to check if text array contains any of the elements find has. I'm able to do this for single text but don't know how to do it for all texts
$counter=0;
foreach($find as $txt){
if (strstr($text[0], $txt)) {
$counter++;
}
如果我用这个方法我得跑的次数的foreach数。是否有任何其他方式做到这一点?
If i use this technique i'll have to run foreach number of times. Is there any other way to do this?
请注意如果数组值中包含或和,没有不整字匹配
的http://$c$cpad.viper-7.com/VKBMtP
输入
$find=array('or','and','not');
$text=array('jasvjasvor','asmasn','tekjbdkcjbdsnot');
// array values "jasvjasvor" and "tekjbdkcjbdsnot" contains words `or,not`
输出
2 - >从发现阵列两个词都包含在文本数组值
2 -> as two words from find array are contained in text array values
推荐答案
使用 array_intersect()
:
if (count(array_intersect($find, $text)) >= 1) {
// both arrays have at least one common element
}
更新::如果你想找到 $文本有多少元素
阵列包含任何值(部分匹配或whole-在 $字匹配)找到
阵列,可以使用以下解决方案:
UPDATE: If you're trying to find how many elements in $text
array contain any of the values (partial match or whole-word match) in $find
array, you can use the following solution:
$counter = 0;
foreach($find as $needle) {
foreach ($text as $haystack) {
if(strpos($haystack, $needle) !== false) $counter++;
}
}
echo $counter; // => 2
这篇关于检查数组包含有另一个数组元素的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!