PHP:精确匹配的正则表达式

发布于 2025-01-08 03:27:15 字数 751 浏览 0 评论 0原文

这是我目前拥有的正则表达式(哪种有效):

$regex = '/[\w ]{7,30}/';

我的修订版看起来像我想要的,但它根本不起作用:

$regex = '^[\w ]{7,30}$';

这是我使用正则表达式的方式:

public function isValid( $value )
{

    $regex = '/^[\w ]{7,30}$/';
    return preg_match( $regex, $value ) ? true : false;

}

我试图匹配以下内容:

  • 任何较低/大写字母
  • 任何数字
  • 可以包含空格
  • 不能包含换行符或制表符空格
  • 最少 7 个字符
  • 最多 30 个字符

有效输入:

  • Testing
  • Test ing
  • Test123
  • Test 123
  • Test___

无效输入:

  • Testing#
  • Testin8+
  • 测试仪1&

第一个正则表达式将匹配所有有效输入以及无效输入(只要前四个字符有效,它不关心其余字符)。第二个正则表达式没有匹配任何内容。

Here is the regex I currently have (which kind of works):

$regex = '/[\w ]{7,30}/';

My revision looks like what I want, but it does not work at all:

$regex = '^[\w ]{7,30}

Here is how I am using the regex:

public function isValid( $value )
{

    $regex = '/^[\w ]{7,30}$/';
    return preg_match( $regex, $value ) ? true : false;

}

I am trying to match the following:

  • Any lower/upper case letter
  • Any digit
  • Can contain spaces
  • Cannot contain line breaks or tab space
  • Minimum of 7 characters
  • Maximum of 30 characters

Valid inputs:

  • Testing
  • Test ing
  • Test123
  • Test 123
  • Test___

Invalid inputs:

  • Testing#
  • Testin8+
  • Tester1&

The first regex will match all valid inputs, as well as invalid (as long as the first four characters are valid, it doesn't care about the rest). The second regex matches nothing.

;

Here is how I am using the regex:

I am trying to match the following:

  • Any lower/upper case letter
  • Any digit
  • Can contain spaces
  • Cannot contain line breaks or tab space
  • Minimum of 7 characters
  • Maximum of 30 characters

Valid inputs:

  • Testing
  • Test ing
  • Test123
  • Test 123
  • Test___

Invalid inputs:

  • Testing#
  • Testin8+
  • Tester1&

The first regex will match all valid inputs, as well as invalid (as long as the first four characters are valid, it doesn't care about the rest). The second regex matches nothing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

り繁华旳梦境 2025-01-15 03:27:15

尝试将两者结合起来,如下所示:

$regex = '/^[\w ]{7,30}$/';

Try combining both like so:

$regex = '/^[\w ]{7,30}$/';
逐鹿 2025-01-15 03:27:15

不要忘记分隔符:

/^[\w ]{7,30}$/

Don't forget your delimiters:

/^[\w ]{7,30}$/

夕色琉璃 2025-01-15 03:27:15

您缺少开头和结尾的 /

$regex = '/^[\w ]{7,30}$/';

You're missing the / at the beginning and end.

$regex = '/^[\w ]{7,30}$/';
想你只要分分秒秒 2025-01-15 03:27:15
'/^[\w ]{7,30}$/'

您缺少分隔符。

'/^[\w ]{7,30}$/'

You're missing the delimiters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文