How to match URLs?

URL matching is another regular expression headache, but I’ve included some of the more useful ones down below to help you get started matching your input.

The simplest that works really well

Regex: ^(https?|ftp)://[^\s/$.?#].[^\s]*$

Another simple one that works quite well

Regex: ^(https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?$

Mathias Bynens has posted an exhaustive comparison of various regular expressions for matching URLs on his site. I’d recommend you check that out for more examples that can catch more complex cases – Alot of them run quite slowly though and might not work on PHP Live Regex.



×

Subscribe

The latest tutorials sent straight to your inbox.