我无法让 preg_match 测试整个字符串是否与正则表达式匹配 [英] I can't get preg_match to test if the entire string matches the regex

查看:66
本文介绍了我无法让 preg_match 测试整个字符串是否与正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个正则表达式来测试用户名是否有效:

I'm using this regular expression to test if a username is valid:

[A-Za-z0-9 _]{3,12} 当我在文本编辑器中使用字符串 test'ing 测试它是否匹配时,它突出显示test"和ing",但是当我在 PHP 中使用以下代码时:

[A-Za-z0-9 _]{3,12} when I test it for matches in a text editor with the string test'ing, it highlights 'test' and 'ing', but when I use the following code in PHP:

if(!preg_match('/[A-Za-z0-9 _]{3,12}/', $content) 其中 $content 是 test'ingcode>,它应该返回 FALSE,它仍然返回 true.

if(!preg_match('/[A-Za-z0-9 _]{3,12}/', $content) where $content is test'ing and it should return FALSE, it still returns true.

我的正则表达式有问题吗?我需要:

Is there something wrong with my regular expression? I need:

  • 最小长度 3,最大 12 {3,12}
  • 字符串前后不得有空格/下划线,且行中任何地方不得有空格/下划线(我为此使用了额外的检查,因为我不太擅长正则表达式)
  • 只允许使用字母数字、空格和下划线 [A-Za-z0-9 _]

提前致谢...

推荐答案

您缺少正则表达式中的锚点,因此正则表达式可以轻松匹配字符类 anywhere 中的 3 个字符细绳.这不是你想要的.您想检查您的正则表达式是否与整个字符串匹配.为此,您需要包含锚点(^$).

You're missing the anchors in the regular expression, so the regex can comfortably match 3 characters in the character class anywhere in the string. This is not what you want. You want to check if your regex matches against the entire string. For that, you need to include the anchors (^ and $).

if(!preg_match('/^[A-Za-z0-9 _]{3,12}$/', $content)
                 ^                   ^

^ 断言字符串开头的位置,$ 断言字符串末尾的位置.需要注意的是,这些元字符实际上并不消耗字符.它们是零宽度断言.

^ asserts the position at the beginning of the string and $ asserts position at the end of the string. It's important to note that these meta characters do not actually consume characters. They're zero-width assertions.

进一步阅读:

这篇关于我无法让 preg_match 测试整个字符串是否与正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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