【问题标题】:Find exact string inside a string在字符串中查找确切的字符串
【发布时间】:2013-04-29 16:38:43
【问题描述】:

我有两个字符串“Mures”和“Maramures”。我如何构建一个搜索功能,当有人搜索 Mures 时,它只会返回包含“Mures”字的帖子,而不是包含“Maramures”字的帖子。直到现在我都尝试了 strstr,但它现在可以工作了。

【问题讨论】:

  • 区分大小写吗? Muresmures 一样吗?
  • 您必须编写代码来创建搜索功能。 php.net

标签: php string


【解决方案1】:

您可以使用正则表达式执行此操作,并用 \b 单词边界包围单词

preg_match("~\bMures\b~",$string)

示例:

$string = 'Maramures';
if ( preg_match("~\bMures\b~",$string) )
  echo "matched";
else
  echo "no match";

【讨论】:

  • 看到您使用的是~ 而不是/,我感到很困惑。但我发现:“经常使用的分隔符是正斜杠/、井号# 和波浪号~。”所有方法都对分隔模式有效。我只需要通过在最后添加i 来使用不敏感参数:preg_match("~\bMures\b~i",$string)
【解决方案2】:

使用 preg_match 函数

if (preg_match("/\bMures\b/i", $string)) {
    echo "OK.";
} else {
    echo "KO.";
}

【讨论】:

    【解决方案3】:

    如何检查 strstr 的结果?在这里试试这个:

    $string = 'Maramures';
    $search = 'Mures';
    $contains = strstr(strtolower($string), strtolower($search)) !== false;
    

    【讨论】:

      【解决方案4】:

      也许这是一个愚蠢的解决方案,但有更好的解决方案。但是您可以在字符串的开头和结尾处为源字符串和目标字符串添加空格,然后搜索“Mures”。易于实现,无需使用任何其他功能:)

      【讨论】:

        【解决方案5】:

        你可以做各种各样的事情:

        • 搜索“Mures”(周围有空格)
        • 搜索区分大小写(因此“mures”会在“Maramures”中找到,但“Mures”不会)
        • 使用正则表达式在字符串中搜索('word boundary + Mures + word boundary')——也看看这个:Php find string with regex

        【讨论】:

          【解决方案6】:
          function containsString($needle, $tag_array){
              foreach($tag_array as $tag){
                  if(strpos($tag,$needle) !== False){
                      echo $tag . " contains the string " . $needle . "<br />";
                  } else {        
                      echo $tag . " does not contain the string " . $needle;
                  }
          
              }
          }
          $tag_array = ['Mures','Maramures'];
          $needle    = 'Mures';
          containsString($needle, $tag_array);
          

          这样的功能会起作用......不过可能不像preg_match那么性感。

          【讨论】:

            【解决方案7】:

            很简单的方法应该和这个差不多。

                $stirng = 'Mures';
            
                if (preg_match("/$string/", $text)) {
                    // Matched
                } else {
                    // Not matched
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-10-10
              • 2011-01-11
              • 1970-01-01
              • 1970-01-01
              • 2014-08-13
              相关资源
              最近更新 更多