How do ensure a partial match doesn't exist between a string and an array?
Right now I am using the syntax:
if ( !array_search( $operating_system , $exclude ) ) {
where the value of $operating_system has extraneous details and will never be just bot , crawl or spider.
As an example the value of $operating_system is
"Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)"
$exclude is an array of unwanted items
$exclude = [
'bot',
'crawl',
'spider'
];
I would like this example to fail the IF because bot is contained in both the string and is an array element.
This code should work nicely for you.
Just call the arraySearch function with the user agent string as the first parameter and the array of text to exclude as the second parameter. If a text in the array is found in the user agent string then the function returns a 1. Otherwise it returns a 0.
function arraySearch($operating_system, $exclude){
if (is_array($exclude)){
foreach ($exclude as $badtags){
if (strpos($operating_system,$badtags) > -1){
return 1;
}
}
}
return 0;
}
Here is a simple regular expression solution:
<?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';
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With