php preg_match url正则表达式无效

时间:2011-11-15 05:55:34

标签: php regex url preg-match

我无法正常使用此功能:

function isValidURL($url){
 return preg_match('%http://domain\.com/([A-Za-z0-9.-_]+)/([A-Za-z0-9.-_]+)%', $url);
}

网址:

http://domain.com/anything-12/anything-12/

可以包含数字,字母和符号_ -

我认为它与第一个正则表达式有关 - 因为这些工作

    http://domain.com/anything12/anything12/

    http://domain.com/anything12/anything-12/

    http://domain.com/anything12/any-thing-12/

    http://domain.com/anything_12/any-thing-12/

一如既往,所有的帮助都会受到赞赏并提前感谢。

1 个答案:

答案 0 :(得分:5)

  1. 您需要在正则表达式的字符类中转义-

  2. 您需要锚定正则表达式,以便尝试匹配整个输入字符串而不是它的一部分。

  3. 修改后的正则表达式是:

    '%^http://domain\.com/([A-Za-z0-9.\-_]+)/([A-Za-z0-9.\-_]+)/$%'
    

    您可以通过注意[A-Za-z0-9_]\w相同并且还有重复的子正则表达式来缩短正则表达式。

    '%^http://domain\.com(/[\w.-]+){2}/$%'