0

I need something like this

$keywords = array('google', 'yahoo', 'facebook');

$mystring = 'alice was going to the yahoo CEO and couldn't him her';

$pos = strpos($mystring, $keywords);

if ($pos === false) {
    echo "The string '$keywords' was not found in the string '$mystring'";
} 

Basically I need to search several terms in a string if find if any exists in the string.

I'm wondering if it would be possible to set the keywords /search to case insensitive

2

1 Answer 1

1

Just iterate over the keywords and stop when you find at least one:

$found = false;

foreach ($keywords as $keyword) {
    if (stripos($mystring, $keyword) !== false) {
        $found = true;
        break;
    }
}

if (!$found) {
    echo sprintf("The keywords '%s' were not found in string '%s'\n",
        join(',', $keywords),
        $mystring
    );
}

Alternatively, use regular expressions with an alternation:

$re = '/' . join('|', array_map(function($item) {
    return preg_quote($item, '/');
}, $keywords)) . '/i';

if (!preg_match($re, $mystring)) {
        echo "Not found\n";
}
Sign up to request clarification or add additional context in comments.

3 Comments

does it still work if I have amazon in the keywords but amazon.com in the content/string ? or amazon in the keywords and Amazon in the string ?
@DoingThings Did you try that?
@Doing nope, it's case insensitive.

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.