regular expression for validating url with sub-dom

2019-09-05 13:42发布

preg_match('/^(http:\\/\/)?(.+)\.MYDOMAIN\.com(.*)/', $url, $match)

This is my regex to validate a URL that must have a sub-domain, but if someone uses www instead of sub-domain it also gets validated. For example:

  • http://shoes.en.MYDOMAIN.com/ This must pass

  • http://www.MYDOMAIN.com/ This must fail

How can I edit my regex to fail if the sub-domain is www?

3条回答
仙女界的扛把子
2楼-- · 2019-09-05 14:17

I think you can do it with a negative lookahead assertion: (?!www\.) which being placed after the protocol check, checks if there is not a www. following the start or protocol.

/^(http:\\\/\/)?(?!www\.)(.+)\.MYDOMAIN\.com(.*)/.test("www.MYDOMAIN.com")
查看更多
神经病院院长
3楼-- · 2019-09-05 14:27

How about first validate the domain using your current solution then check for www using a second expression:

(\.www\.|http:\/\/www\.|^www\.)
查看更多
趁早两清
4楼-- · 2019-09-05 14:28

try this one: tested a litle, seems to be working

preg_match('/^(http:\\/\/)?([^(www)]+)\.MYDOMAIN\.com(.*)/', $url, $match);
查看更多
登录 后发表回答