Php 在字符串中查找精确的字符串

Php 在字符串中查找精确的字符串,php,string,Php,String,我有两个字符串“Mures”和“Maramures”。我如何构建一个搜索功能,当有人搜索Mures时,它将只返回包含“Mures”单词的帖子,而不返回包含“Maramures”单词的帖子。我一直在尝试strstr,但现在它仍然有效。如何检查strstr的结果?在这里试试这个: $string = 'Maramures'; $search = 'Mures'; $contains = strstr(strtolower($string), strtolower($search)) !== fals

我有两个字符串“Mures”和“Maramures”。我如何构建一个搜索功能,当有人搜索Mures时,它将只返回包含“Mures”单词的帖子,而不返回包含“Maramures”单词的帖子。我一直在尝试strstr,但现在它仍然有效。

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

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

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

preg\u match(“~\bMures\b~”,$string)

示例:

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

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

使用预匹配功能

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

您可以做各种事情:

  • 搜索“Mures”(周围的空格)
  • 搜索区分大小写(因此“mures”会出现在“Maramures”中,但“mures”不会)
  • 使用正则表达式在字符串中搜索('word boundary+Mures+word boundary')--也请看一下:
函数包含字符串($needle,$tag\u数组){
foreach($tag_数组作为$tag){
if(strpos($tag,$needle)!==False){
echo$tag.。包含字符串“$pinder”。
; }否则{ echo$标记。“不包含字符串”。$指针; } } } $tag_数组=['Mures','Maramures']; $needle='Mures'; 包含字符串($Pineder,$tag_数组);

这样的函数会起作用。。。可能没有preg\u match性感。

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

    $stirng = 'Mures';

    if (preg_match("/$string/", $text)) {
        // Matched
    } else {
        // Not matched
    }

它区分大小写吗?
Mures
Mures
是否相同?您必须编写代码才能创建搜索功能。看到您使用的是
~
而不是
/
,我感到很困惑。但我发现:“经常使用的分隔符是前斜杠
/
,散列符号
#
和tildes
~
”所有方法都对分隔模式有效。我只需要在末尾添加
I
而不使用敏感参数:
preg\u match(“~\bMures\b~I”,$string)
    $stirng = 'Mures';

    if (preg_match("/$string/", $text)) {
        // Matched
    } else {
        // Not matched
    }