Php 搜索文本以确定它是否包含我正在搜索的单词的最佳方法是什么?
如果它只是搜索一个单词,那就很容易了,但指针可以是一个单词,也可以是多个单词Php 搜索文本以确定它是否包含我正在搜索的单词的最佳方法是什么?,php,string,substring,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',
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'
谢谢,您可以迭代$words_eg1、2、3的元素,并在
strpos
或strstr
返回非假值时立即停止。在您的情况下stripos()
可能会起到以下作用:
function is_words_in_text($words, $string)
{
foreach ((array) $words as $word)
{
if (stripos($string, $word) !== false)
{
return true;
}
}
return false;
}
但这也将匹配非单词(如te
中的Water
),要解决这一问题,我们可以使用preg\u match()
:
所有搜索都是以不区分大小写的方式进行的,
$words
可以是字符串或数组。您是否考虑过strpos:,请检查下面的示例。可能重复我投票关闭,但这个问题有点不同,因为它涉及不区分大小写的字符串和单词边界-由您决定。
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;
}