PHP Match Array against Partial String PHP Match Array against Partial String arrays arrays

PHP Match Array against Partial String


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 patternif ( !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';?>