0
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
  • Use backticks to format URLs: http://www.MYDOMAIN.com/. That will stop SO from linkifying them, and from dropping the http:// in comments. Commented Apr 12, 2012 at 11:31

3 Answers 3

2

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")
Sign up to request clarification or add additional context in comments.

2 Comments

This is getting failed when i use http. The regex is passing sd.MYDOMAIN.com It must be failed as it has www
shoes.trustpass.MYDOMAIN.com why is this getting pass??? It works fine if I remove http://. After submitting stackoverflow removes http and www from the url. Kindly add http and www at starting of provided URL
0

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

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

4 Comments

Does not do what you are expecting. The www is actually treated as character class, so equivalent to w and matches any subdomain that does not contain a w.
you are also missing an escaping slash in the protocol
This is getting failed if my subdomain starts with www. Like wwwshoes
It even fails if subdomian has www anywhere in it.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.