8

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.

1
  • 4
    Use a regexp instead of a string list. Commented Sep 13, 2015 at 3:17

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

If you want the case insensitive match, then simply insert an i character exactly after the second # :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.