Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 搜索文本以确定它是否包含我正在搜索的单词的最佳方法是什么?_Php_String_Substring - Fatal编程技术网

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;
}