繁体   English   中英

PHP 匹配字符串中的单词数组

[英]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 - 您只需要在使用 NO 的地方将Status更改为 YES。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM