【问题标题】:Check and compare two strings in PHP在 PHP 中检查和比较两个字符串
【发布时间】:2015-12-11 06:50:24
【问题描述】:

我想检查两个字符串。我想使用该方法检查两个字符串之间的相似性或匹配性。

例子:

$str1 = "Samsung Galaxy Note 5";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

我希望结果是匹配的,因为两个字符串都有关键字“Samsung Galaxy Note 5”。

另一个例子:

$str1 = "Samsung Galaxy Note 4";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

结果不匹配,因为两个字符串没有相同的关键字。

我可以使用什么方法?

【问题讨论】:

  • MySQL 代码 ??还是php??
  • 第二个例子怎么没有?三星 Galaxy 比赛。

标签: php string string-matching


【解决方案1】:

你可以试试这个——

$str1 = "Samsung Galaxy Note 4";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

if(strpos(str_replace(' ', '', $str2), str_replace(' ', '', $str1)) !== 0) {
   echo "Not Matched!";
}

对于您提供的示例,它应该可以工作。

【讨论】:

    【解决方案2】:

    由于您匹配的是 NOTE 5 和 NOTE5,所以您需要替换空格并使用 strpos

    $str1 = "Samsung Galaxy Note 5";
    $str1 = str_replace(" ", "", $str1);
    $str2 = "Samsung Galaxy Note 5 Black Smartphone";
    $str2 = str_replace(" ", "", $str2);
    
    if (strpos($str2,$str1) !== false) {
        echo 'true';
    }else{
    echo "not found";
    }
    

    【讨论】:

      【解决方案3】:

      您可以将preg_matchpreg_replace 一起使用

      $str1 = "Samsung Galaxy Note 5";
      $str2 = "Samsung Galaxy Note5 Black Smartphone";
      
      if(preg_match("/(".preg_replace('/[\h]/','',$str1).")/i",preg_replace('/[\h]/','',$str2))!==false){
          echo "match";
      }
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多