-4

如果条件:

if (preg_match('/^[a-zA-Z_]+\z/', $network_path)) 

跳过字符串,例如:bla-bla-bla-bla

我怎样才能改进这个正则表达式,让它接受像上面这样的字符串..?

4

3 回答 3

2

[a-zA-Z_]是一个字符类。此构造匹配方括号内定义的字符中的一个字符。

所以这个类匹配 a 到 z、A 到 Z 和下划线。如果你还想匹配一个破折号,你只需要将它添加到类中。但要小心,-是字符类中的特殊字符,所以如果你想从字面上匹配它,你需要将它转义或将它放在类的开头或结尾。

if (preg_match('/^[-a-zA-Z_]+\z/', $network_path))

或者

if (preg_match('/^[a-zA-Z_-]+\z/', $network_path))

或者

if (preg_match('/^[a-zA-Z\-_]+\z/', $network_path))
于 2012-04-18T11:07:07.830 回答
1
if (preg_match('/^[-a-zA-Z_]+\z/', $network_path)) 
于 2012-04-18T10:59:26.437 回答
1

(不是 PHP 人,所以 ymmv,但是......)

The characters inside the [] are treated as a character class by most perl compatible regex engines. Character classes can be followed my modifiers like the +, which will accept 1 or more characters from within that class. So if you simply add the dash inside the character class, you should get what you're looking for (or at least, you do in ruby!)

于 2012-04-18T11:09:42.727 回答