有没有办法将 preg_match 与总字符串长度结合起来?我需要能够匹配字母数字,字符串内有单个下划线,总字符串长度<= n。
目前我正在使用的是:
preg_match('/^[A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/',$string) && (strlen($string) <= 10)
我已经玩这个太久了,试图将整个事情合并到 preg_match 中,所以只是添加了&& strlen
,但我确信有更好的方法来做到这一点。
有没有办法将 preg_match 与总字符串长度结合起来?我需要能够匹配字母数字,字符串内有单个下划线,总字符串长度<= n。
目前我正在使用的是:
preg_match('/^[A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/',$string) && (strlen($string) <= 10)
我已经玩这个太久了,试图将整个事情合并到 preg_match 中,所以只是添加了&& strlen
,但我确信有更好的方法来做到这一点。
试一试:
preg_match('/^(?=[A-Za-z0-9]*(?:_[A-Za-z0-9]+)*).{1,10}$/', $string)
根据评论编辑:
/^(?=[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*$).{5,25}$/
解释:
The regular expression:
(?-imsx:^(?=[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*$).{5,25}$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
[A-Za-z0-9]+ any character of: 'A' to 'Z', 'a' to
'z', '0' to '9' (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the most amount
possible)):
----------------------------------------------------------------------
_ '_'
----------------------------------------------------------------------
[A-Za-z0-9]+ any character of: 'A' to 'Z', 'a' to
'z', '0' to '9' (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
.{5,25} any character except \n (between 5 and 25
times (matching the most amount possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------