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

标签 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'

谢谢,

最佳答案

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

关于php - 搜索文本以确定它是否包含我正在搜索的单词的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5845034/

相关文章:

PHP:为什么将日期字符串转换为时间戳然后再转换回日期字符串不起作用?

php - 如何在php中设置当前页面 "active"

php7 :error pid 12451 PHP Fatal error: require(): Failed opening required

python - 使用正则表达式捕获 Python 脚本中的所有字符串

C:使用 strcmp

string - 为什么不使用 %v 来打印 int 和 string

c - 从C中的一行中读取带有空格的子字符串

ios - 从 <span to > 中提取 NSString 的一部分,其间有可变字符

php - MySQL 未添加到数据库

mysql - 选择填充数据的列中的所有唯一电子邮件