Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Match Array against Partial String

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.

like image 826
Ron Piggott Avatar asked Sep 13 '15 03:09

Ron Piggott


2 Answers

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;
}
like image 122
Mike -- No longer here Avatar answered Oct 02 '22 09:10

Mike -- No longer here


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';
?>
like image 42
someOne Avatar answered Oct 02 '22 07:10

someOne