开发者

PHP search word in string

I'm trying to scan a piece of text for the occurrence of certain words. If the string contains any of these words, the function should return TRUE. in_array can accept two arrays but it seems that all elements of the needle need to be found in the haystack for the return to be TRUE.

From the user manual - returns TRUE

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
   return TRUE
}

But this doesn't re开发者_Python百科turn TRUE.

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'x'), $a)) {
    return TRUE
}

I can write the function with an if/else for every word I want to find but that seems a bit cumbersome. Is there a better way, perhaps with regex?

Background: the text I'm searching in is about 200 words max, so I explode on " " to make an array in which I then search.


function strExists($value, $string)
{
    foreach ((array) $value as $v) {
        if (false !== strpos($string, $v)) return true;
    }
}


in_array(array('p', 'h'), $a)

looks for an array in $a, not for two strings 'p' and 'h'. Use explode(), array_flip() and isset() instead:

$haystack = array_flip(explode(' ', $str));
$needles = array('p', 'h');

foreach ($needles as $needle) {
    if (isset($haystack[$needle])) {
        // ...
    }
}


This regex returns TRUE if word1, word2 OR word3 is found anywhere in $str. No need to split the string at all and it’s case-insensitive.

preg_match('/word1|word2|word3/i', $str);


You are missing ; after the code return TRUE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜