简体   繁体   中英

php search string in another string from array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM