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


What is best way to search a text to determine if it contains the word (or words) I am searching for?

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

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'

谢谢你,

在您的情况下,stripos()可能会做到这一点:

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

但这也将匹配非单词(如Water中的te),为了解决这个问题,我们可以使用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可以是字符串或数组。

可以迭代$words_eg1、2,3的元素,只要strposstrstr返回一个非假值就停止。