Search code examples
phpregexurl

Regex pattern to match a URL


I'm trying to make a regular expression that kind of looks like a URL. I only want basic checking.

I would like it to match the following patterns where X is "something".

X://X.X

X://X.X... etc.

X.X

X.X... etc

If the string contains one of these patterns, it is sufficient checking for me. This way a url like www.example.com:8888 will still match. I have tried many different REGEX combinations with preg_match and cannot seem to get any to behave the way I want it to. I have consulted many other related REGEX questions on SO but my readings have not helped me.


Solution

  • It takes practice but here is one that I made using a regex tester (http://www.regextester.com/) to check my pattern:

    ^.+(:\/\/|\.)([a-zA-Z0-9]+\.)+.+
    

    My approach is to slowly build my pattern from the beginning and add on one piece at a time. This cheatsheet is extremely helpful for remembering http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ what everything is.

    Basically the pattern starts at the beginning of the string and checks for any characters followed by either :// or . then checks for groupings of letters and numbers followed by a . ending with any number of characters.

    The pattern could probably be improved with groupings to not pass on invalid characters. But this one was quick and dirty. You could replace the first and last . with the characters that would be valid.

    UPDATE

    Per the comments here is an updated pattern:

    ^.+?(:\/\/|\.)?([a-zA-Z0-9]+?\.)+.+