8

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

4

7 回答 7

20

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

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

例子:

$string = 'Maramures';
if ( preg_match("~\bMures\b~",$string) )
  echo "matched";
else
  echo "no match";
于 2013-04-29T16:41:24.920 回答
6

使用 preg_match 函数

if (preg_match("/\bMures\b/i", $string)) {
    echo "OK.";
} else {
    echo "KO.";
}
于 2013-04-29T16:42:26.013 回答
1

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

$string = 'Maramures';
$search = 'Mures';
$contains = strstr(strtolower($string), strtolower($search)) !== false;
于 2013-04-29T16:41:16.750 回答
0

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

  • 搜索“ Mures ”(周围有空格)
  • 搜索区分大小写(所以 'mures' 将在 'Maramures' 中找到,但 'Mures' 不会)
  • 使用正则表达式在字符串中搜索('word boundary + Mures + word boundary')——也看看这个:Php find string with regex
于 2013-04-29T16:43:09.827 回答
0

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

于 2013-04-29T16:42:02.550 回答
0
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

于 2013-04-29T16:51:06.407 回答
0

非常简单的方法应该与此类似。

    $stirng = 'Mures';

    if (preg_match("/$string/", $text)) {
        // Matched
    } else {
        // Not matched
    }
于 2019-11-26T11:24:34.423 回答