如果只是搜索一个单词,那就很容易了,但是针可以是一个单词,也可以是多个单词。
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/