匹配字符串中的单词数组


PHP Match array of words in string

我有一个单词/短语数组,我想在字符串中匹配。如果在字符串我想插入到一个数据库表,但它必须匹配整个字符串或短语。例如:

$string = "This is a Sample sting of information"; 
$words = array('This is', 'Test', 'sample', 'information', 'sting of information');

因此它将匹配:这是样本信息信息序列

也不区分大小写。

我已经走了这么远,但我卡住了:

$string = "This is a Sample sting of information"; 
$words = array('This is', 'Test', 'sample', 'information', 'sting of information');        
foreach ($words as $word) {
        if (strstr($string,$word) !== false) {
            echo $word." - NO<br>";
        }
        else {
            echo $word." - YES<br>";
        }
    }

我想,你认为if (strstr($string,$word) !== false) {这将返回False?

不,如果找到关键字或短语,这将返回TRUE。

你需要什么?

1 -您只需要将您的Status更改为YES,而您使用的是NO。

2 -在你使用YES的地方将你的状态更改为NO

3 -对于不区分大小写的值,可以使用stristr()

修改的例子:

<?php
$string = "This is a Sample sting of information"; 
$words = array('This is', 'Test', 'sample', 'information', 'sting of informtaion');        
foreach ($words as $word) {
  var_dump(stristr($string,$word) !== false); // this will help you to understand, what is happening here.
  if (stristr($string,$word) !== false) {
      echo $word." - YES<br>";
  }
  else {
      echo $word." - NO<br>";
  }
}
?>

还要注意,正如@CD001在评论中所说,你有一个错字information != informtaion

注意,strstr()是一个区分大小写的函数,对于不区分大小写的函数,您需要stristr();

试试这个

foreach ($words as $word) {
 if(stripos($string, $word) !== false) {
    echo "Yes"."<br>";
 }else{
   echo "no";
 }
}