搜索文本以确定它是否包含我要搜索的单词(或单词)的最佳方法是什么?

时间:2011-04-30 22:27:42

标签: php string substring

如果它只是搜索一个单词,那就很容易了,但针可以是一个单词,也可以是一个单词。

Example
 $text = "Dude,I am going to watch a movie, maybe 2c Rio 3D or Water for Elephants, wanna come over";
 $words_eg1 = array ('rio 3d', 'fast five', 'sould surfer');
 $words_eg2 = array ('rio', 'fast five', 'sould surfer');
 $words_eg3 = array ('Water for Elephants', 'fast five', 'sould surfer');

'
 is_words_in_text ($words_eq1, $text)   / true, 'Rio 3D' matches with 'rio 3d'
 is_words_in_text ($words_eq2, $text)   //true, 'Rio' matches with 'rio'
 is_words_in_text ($words_eq3, $text)   //true, 'Water for Elephants'

谢谢,

2 个答案:

答案 0 :(得分:3)

在您的情况下,stripos()可能会解决问题:

function is_words_in_text($words, $string)
{
    foreach ((array) $words as $word)
    {
        if (stripos($string, $word) !== false)
        {
            return true;
        }
    }

    return false;
}

但这也会匹配非单词(如te中的Water),为了解决此问题,我们可以使用preg_match()

function is_words_in_text($words, $string)
{
    foreach ((array) $words as $word)
    {
        if (preg_match('~\b' . preg_quote($word, '~') . '\b~i', $string) > 0)
        {
            return true;
        }
    }

    return false;
}

所有搜索都以不区分大小写的方式完成,$words可以是字符串或数组。

答案 1 :(得分:0)

您可以迭代$ words_eg1,2,3的元素,并在strposstrstr返回非假值时立即停止。

相关问题