简体   繁体   English

PHP 4个字符的正则表达式

[英]php regular expression for 4 characters

I am trying to construct a regular expression for a string which can have 0 upto 4 characters. 我正在尝试为一个字符串构造一个正则表达式,该字符串可以具有0到4个字符。 The characters can only be 0 to 9 or a to z or A to Z. 字符只能是0到9或a到z或A到Z。

I have the following expression, it works but I dont know how to set it so that only maximum of 4 characters are accepted. 我有以下表达式,它可以工作,但是我不知道如何设置它,这样最多只能接受4个字符。 In this expression, 0 to infinity characters that match the pattern are accepted. 在该表达式中,接受0到与模式匹配的无穷大字符。

'([0-9a-zA-Z\s]*)'

You can use {0,4} instead of the * which will allow zero to four instances of the preceding token: 您可以使用{0,4}代替* ,这将允许零至四个上述标记的实例:

'([0-9a-zA-Z\s]{0,4})'

( * is actually the same as {0,} , ie at least zero and unbounded.) *实际上与{0,}相同,即至少为零且无界。)

You can use { } to specify finite quantifiers: 您可以使用{ }指定有限量词:

[0-9a-zA-Z\s]{0,4}

http://www.regular-expressions.info/reference.html http://www.regular-expressions.info/reference.html

If you want to match a string that consists entirely of zero to four of those characters, you need to anchor the regex at both ends: 如果要匹配一个完全由零到四个这些字符组成的字符串,则需要在两端固定正则表达式:

'(^[0-9a-zA-Z]{0,4}$)'

I took the liberty of removing the \\s because it doesn't fit your problem description. 我随意删除\\s因为它不适合您的问题描述。 Also, I don't know if you're aware of this, but those parentheses do not form a group, capturing or otherwise. 另外,我不知道您是否知道这一点,但是这些括号不会形成一个组,无法捕获。 They're not even part of the regex; 它们甚至都不是正则表达式的一部分。 PHP is using them as regex delimiters. PHP将它们用作正则表达式分隔符。 Your regex is equivalent to: 您的正则表达式等效于:

'/^[0-9a-zA-Z]{0,4}$/'

If you really want to capture the whole match in group #1, you should add parentheses inside the delimiters: 如果您确实要捕获组#1中的整个匹配项,则应在定界符添加括号:

'/(^[0-9a-zA-Z]{0,4}$)/'

... but I don't see why you would want to; ...但是我不明白你为什么要这么做; the whole match is always captured in group #0 automatically. 整个比赛总是自动在#0组中进行。

You can avoid regular expressions completely. 您可以完全避免使用正则表达式。

if (strlen($str) <= 4 && ctype_alnum($str)) {
   // contains 0-4 characters, that are either letters or digits
}

ctype_alnum()

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

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