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

时间:2022-02-22 18:55:46

If it was just searching for a single word, it would have been easy, but the needle can be a word or more than a word.

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

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'

Thank you,

2 个解决方案

#1


3  

In your case stripos() will probably do the trick:

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

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

    return false;
}

But this will match also non-words (as in te in Water), to fix this we can use preg_match():

但这也会匹配非单词(如水中的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;
}

All searches are done in a case-insensitive way, $words can either be a string or an array.

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

#2


0  

You could iterate over the elements of $words_eg1, 2, 3 and stop as soon as strpos or strstr returns a non-false value.

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

#1


3  

In your case stripos() will probably do the trick:

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

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

    return false;
}

But this will match also non-words (as in te in Water), to fix this we can use preg_match():

但这也会匹配非单词(如水中的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;
}

All searches are done in a case-insensitive way, $words can either be a string or an array.

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

#2


0  

You could iterate over the elements of $words_eg1, 2, 3 and stop as soon as strpos or strstr returns a non-false value.

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