PHP匹配部分字符串的数组

时间:2015-09-13 03:14:03

标签: php arrays string if-statement

如何确保字符串和数组之间不存在部分匹配?

现在我正在使用语法:

if ( !array_search( $operating_system , $exclude ) ) {

$ operating_system的值有无关的细节,永远不会只是机器人,爬网或蜘蛛。

作为一个例子,$ operating_system的值是

"Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)"

$ exclude是一系列不需要的物品

$exclude = [
    'bot',
    'crawl',
    'spider'
];

我希望此示例使IF失败,因为 bot 包含在字符串中并且是数组元素。

2 个答案:

答案 0 :(得分:3)

此代码应该可以很好地为您服务。

只需使用用户代理字符串作为第一个参数调用arraySearch函数,并将要排除的文本数组作为第二个参数调用。如果在用户代理字符串中找到数组中的文本,则该函数返回1.否则返回0。

function arraySearch($operating_system, $exclude){
    if (is_array($exclude)){
        foreach ($exclude as $badtags){
            if (strpos($operating_system,$badtags) > -1){
                return 1;
            }
        }
    }
    return 0;
}

答案 1 :(得分:3)

这是一个简单的正则表达式解决方案:

<?php
$operating_system = 'Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)';
$exclude = array('bot', 'crawl', 'spider' );

$re_pattern = '#'.implode('|', $exclude).'#'; // create the regex pattern
if ( !preg_match($re_pattern, $operating_system) )
    echo 'No excludes found in the subject string !)';
else echo 'There are some excludes in the subject string :o';
?>
相关问题