【问题标题】:What is best way to search a text to determine if it contains the word (or words) I am searching for?搜索文本以确定它是否包含我正在搜索的单词(或单词)的最佳方法是什么?
【发布时间】:2011-08-16 05:54:41
【问题描述】:

如果只是搜索一个词,那会很容易,但针可以是一个词,也可以不止一个词。

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'

谢谢,

【问题讨论】:

标签: php string substring


【解决方案1】:

您可以遍历 $words_eg1、2、3 的元素,并在 strposstrstr 返回非 false 值时立即停止。

【讨论】:

    【解决方案2】:

    在你的情况下,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 可以是字符串或数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多