regular expression for validating url with sub-domain

守給你的承諾、 提交于 2020-01-06 14:55:28

问题


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?


回答1:


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")



回答2:


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

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



回答3:


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

(\.www\.|http:\/\/www\.|^www\.)


来源:https://stackoverflow.com/questions/10118536/regular-expression-for-validating-url-with-sub-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!