怎么样:
^[a-z][a-z0-9]*(?:-?[a-z0-9]+)*[a-z0-9]$
例子:
$arr = array('ab9cd-a9bc-abbbc95','5abcd','abbcd-','-abcd','abcd--abcd');
foreach($arr as $str) {
if (preg_match('/^[a-z][a-z0-9]*(?:-?[a-z0-9]+)*[a-z0-9]$/', $str)) {
echo "OK : $str\n";
} else {
echo "KO : $str\n";
}
}
输出:
OK : ab9cd-a9bc-abbbc95
KO : 5abcd
KO : abbcd-
KO : -abcd
KO : abcd--abcd
解释:(来自 YAPE::Regex::Explain)
The regular expression:
(?-imsx:^[a-z][a-z0-9]*(?:-?[a-z0-9]+)*[a-z0-9]$)
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
----------------------------------------------------------------------
[a-z] any character of: 'a' to 'z'
----------------------------------------------------------------------
[a-z0-9]* any character of: 'a' to 'z', '0' to '9'
(0 or more times (matching the most amount
possible))
----------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
-? '-' (optional (matching the most amount
possible))
----------------------------------------------------------------------
[a-z0-9]+ any character of: 'a' to 'z', '0' to '9'
(1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
[a-z0-9] any character of: 'a' to 'z', '0' to '9'
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------