如何在字符串中的任何位置匹配精确的单词与PHP正则表达式

如何在字符串中的任何位置匹配精确的单词与PHP正则表达式

问题描述:

I want to find out if user has used the words admin or username anywhere in their possible username string.

So if user wants to use admin, or I am admin, or my admin name or my username, as their username, I want my regexp to detect it. If he uses adminmember I can live with that, don't detect it. I also want detection to be case insensitive.

So far I got this, but it is not really working as I thought, since it will detect words that it shouldn't:

/^[admin|username]+$/i

This will match even adm, and it shouldn't. I have tried with word boundaries, but I couldn't make it work either, maybe I did something wrong. As you can see in my question I would like to detect word admin anywhere in the string, but if it is a part of some word I can skip it.

Thanks in advance.

我想知道用户是否使用过 admin code>或用户名 code>在他们可能的用户名字符串中的任何地方。 p>

因此,如果用户想要使用 admin code>,或我是管理员 code>,或者 我的管理员名称 code>或我的用户名 code>,作为他们的用户名,我希望我的正则表达式能够检测到它。 如果他使用 adminmember code>,我可以忍受,不要检测它。 我也希望检测不区分大小写。 p>

到目前为止,我得到了这个,但它并没有像我想象的那样真正起作用,因为它会检测出它不应该出现的单词: p >

/ ^ [admin | username] + $ / i code> p>

这甚至与 adm code>相匹配, 它不应该。 我尝试过单词边界,但我也无法使它工作,也许我做错了。 正如您在我的问题中所看到的,我想在字符串中的任何地方检测到单词admin,但如果它是某个单词的一部分,我可以跳过它。 p>

提前致谢。 p> div>

Square brackets in a regexp are not for grouping, they're for specifying character classes; grouping is done with parentheses. You don't want to anchor the regexp with ^ and $, because that will only match at the beginning and end of the string; you want to use \b to match word boundaries.

/\b(admin|username)\b/i

Just look for words using word boundaries:

/\b(?:admin|username)\b/i

and if there is a match return error e.g.

if (preg_match('/\b(?:admin|username)\b/i', $input)) {
    die("Invalid Input");
}

Try the below snippet to keep your list of words in Array.

$input = "im username ";
$spam_words = array("admin", "username");
$expression = '/\b(?:' . implode($spam_words, "|") . ')\b/i';

if (preg_match($expression, $input)) {
  die("Username contains invalid value");
}
else {
  echo "Congrats! is valid input";
}

Working Fiddle URL:
http://sandbox.onlinephpfunctions.com/code/6f8e806683c45249338090b49ae9cd001851af49

This might be the pattern that you're looking for:

'#(^|\s){1}('. $needle .')($|\s|,|\.){1}#i'

Some details depend on the restrictions that you want to apply.