如何使用 PHP regexp 匹配字符串中任意位置的确切单词 [英] How to match exact word anywhere in string with PHP regexp

查看:53
本文介绍了如何使用 PHP regexp 匹配字符串中任意位置的确切单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道用户是否在其可能的用户名字符串中的任何位置使用了 adminusername 词.

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

所以如果用户想使用admin,或I am admin,或my admin namemy username>,作为他们的用户名,我希望我的正则表达式能够检测到它.如果他使用 adminmember 我可以忍受,不要检测到它.我还希望检测不区分大小写.

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

这甚至会匹配 adm,但它不应该.我已经尝试过单词边界,但我也无法让它工作,也许我做错了什么.正如您在我的问题中所见,我想检测字符串中任何位置的单词 admin,但如果它是某个单词的一部分,我可以跳过它.

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.

提前致谢.

推荐答案

正则表达式中的方括号不是用于分组,而是用于指定字符类;分组是用括号完成的.您不想使用 ^$ 来锚定正则表达式,因为它们只会匹配字符串的开头和结尾;您想使用 \b 来匹配单词边界.

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

这篇关于如何使用 PHP regexp 匹配字符串中任意位置的确切单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆