简体   繁体   English

PHP-句子中的完全匹配字符串

[英]PHP - Exact match string in a sentence

I have the following function to do a "exact match" of a pattern ($searchPat) in a sentence ($sourceStr) 我具有以下功能来对句子($sourceStr)中的模式($searchPat)进行"exact match"

function isUsed($sourceStr, $searchPat) {
 if (strpos($sourceStr, $searchPat) !== false) {
    return true;
    } else {
    return false;
    }
}

However, this doesn't do an exact match. 但是,这并不完全匹配。 I changed the function as follows but this doesn't even execute. 我按如下方式更改了功能,但这甚至没有执行。

function isUsed($sourceStr, $searchPat) {
if (preg_match("~\b[$sourceStr]\b~", $searchPat)) {
    return true;
    } else {
    return false;
    }
}

How could I do an exact match please? 请问我该怎么做?

The [] is a character class. []是字符类。 That lists characters you want to allow, for example [aeiou] would allow a vowel. 上面列出了您要允许的字符,例如[aeiou]将允许一个元音。 Your variables are also in the inverted order, pattern first, then string to match against. 您的变量也按相反的顺序排列,首先是模式,然后是要匹配的字符串。 Try this: 尝试这个:

function isUsed($sourceStr, $searchPat) {
     if (preg_match("~\b$searchPat\b~", $sourceStr)) {
         return true;
     } else {
         return false;
     }
}

Additional notes, this is case sensitive, so Be won't match be . 其他注意事项,这是区分大小写的,所以Be不匹配be If the values you are passing in are going to have special characters the preg_quote function should be used, preg_quote($variable, '~') . 如果您传入的值将具有特殊字符,则应使用preg_quote函数preg_quote($variable, '~') You also may want to concatenate the variable so it is clear that that is a variable and not part of the regex. 您可能还想连接变量,因此很明显这是一个变量,而不是正则表达式的一部分。 The $ in regex means the end of the string. 正则表达式中的$表示字符串的结尾。

Try This. 尝试这个。

function isUsed($sourceStr, $searchPat) {
if (preg_match("/\b".preg_quote($sourceStr)."\b/i", $searchPat)) {
    return true;
    } else {
    return false;
    }
}

Please try "preg_match" for matches. 请尝试“ preg_match”进行匹配。

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

Or try like this 或者像这样尝试

if(stripos($text,$word) !== false) 
      echo "no match";
    else
      echo "match";

You can try this one: 您可以尝试以下一种方法:

  function isUsed($string_to_search, $source_String) {
    if (preg_match("/$string_to_search/", $source_String)) {
    return true;
    } else {
     return false;
    }
 }

You can change according to your need. 您可以根据需要进行更改。

Case insensitive: preg_match("/$string_to_search/i", $source_String) 不区分大小写: preg_match(“ / $ string_to_search / i”,$ source_String)
Boundry condition: preg_match("/\\b$string_to_search\\b/i", $source_String) 边界条件: preg_match(“ / \\ b $ string_to_search \\ b / i”,$ source_String)
Special characters: if you have any special characters in your string for your safe side replace it with '\\special_character' 特殊字符:如果为了安全起见,字符串中有任何特殊字符,请将其替换为'\\ special_character'

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

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