php preg_match url regex not working


php preg_match url regex not working

我无法使此函数正常工作:

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. 您需要转义您的regex字符类中的-

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

修改后的正则表达式为:

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

你可以缩短你的正则表达式,注意[A-Za-z0-9_]是相同的'w,也有一个重复的子正则表达式。

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