Home » Php » PHP Match Array against Partial String

PHP Match Array against Partial String

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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';
?>

Answer:

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;
}