TimFelix TimFelix - 4 years ago 98
PHP Question

regex to match a URL with optional 'www' and protocol

I'm trying to write a regexp.

some background info: I am try to see if the REQUEST_URI of my website's URL contains another URL. like these:

However, the url wont always contain the 'http' or the 'www'. so the pattern should also match strings like:

there are a bunch of regexps out there to match urls but none I have found do an optional match on the http and www.

i'm wondering if the pattern to match could be something like:


I thought maybe another option was to perhaps just match any string that had a dot (.) in it. (as the other REQUEST_URI's in my application typically won't contain dots)

Does this make sense to anyone?
I'd really appreciate some help with this its been blocking my project for weeks.

Thanks you very much

Answer Source

I suggest using a simple approach, essentially building on what you said, just anything with a dot in it, but working with the forward slashes too. To capture everything and not miss unusual URLs. So something like:


It reads as:

  • optional http:// or https://
  • non-dot-or-forward-slash characters
  • one or more sets of a dot followed by non-dot-or-forward-slash characters
  • optional forward slash and anything after it

Capturing the whole thing to the first grouping.

It would match, for example:

  • nic.uk
  • nic.uk/
  • http://nic.uk
  • http://nic.uk/
  • https://example.com/test/?a=bcd

Verifying they are valid URLs is another story! It would also match:

  • index.php

It would not match:

  • directory/index.php

The minimal match is basically something.something, with no forward slash in it, unless it comes at least one character past the dot. So just be sure not to use that format for anything else.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download