Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

php - 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:

^([a-z]).(com|ca|org|etc)(.)

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 -Tim

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

^((?:https?://)?[^./]+(?:.[^./]+)+(?:/.*)?)$

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...