PHP根据部分字符串匹配数组
如何确保字符串和数组之间不存在部分匹配 现在我正在使用以下语法:PHP根据部分字符串匹配数组,php,arrays,string,if-statement,Php,Arrays,String,If Statement,如何确保字符串和数组之间不存在部分匹配 现在我正在使用以下语法: if ( !array_search( $operating_system , $exclude ) ) { 其中$operating_系统的价值具有无关的细节,永远不会是机器人、爬网或蜘蛛 例如,$operating_system的价值为 "Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)" $exclude是不需要的项目的数组 $exclu
if ( !array_search( $operating_system , $exclude ) ) {
其中$operating_系统的价值具有无关的细节,永远不会是机器人、爬网或蜘蛛
例如,$operating_system的价值为
"Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)"
$exclude是不需要的项目的数组
$exclude = [
'bot',
'crawl',
'spider'
];
我希望这个示例使IF失败,因为bot包含在字符串中,并且是数组元素。这段代码应该对您很有用 只需调用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;
}
下面是一个简单的正则表达式解决方案:
<?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';
?>
使用regexp而不是字符串列表。如果需要不区分大小写的匹配,只需在第二个
#
:)后面插入一个i
字符即可