Ron*_*ott 8 php arrays string if-statement
如何确保字符串和数组之间不存在部分匹配?
现在我正在使用语法:
if ( !array_search( $operating_system , $exclude ) ) {
Run Code Online (Sandbox Code Playgroud)
其中$ operating_system的值具有无关的细节,永远不会只是机器人,爬行或蜘蛛.
作为一个例子,$ operating_system的值是
"Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)"
Run Code Online (Sandbox Code Playgroud)
$ exclude是一组不需要的项目
$exclude = [
'bot',
'crawl',
'spider'
];
Run Code Online (Sandbox Code Playgroud)
我想这个例子使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;
}
Run Code Online (Sandbox Code Playgroud)