Search code examples
phppreg-match-all

preg_match_all - regex to find full urls in string


I have spent over 4 hours trying to find a regex patter to my php code without luck.

I have a string with html code. It has lot of urls formats like:

example.com
http://example.com
http://www.example.com
http://example.com/some.php
http://example.com/some.php?var1=1
http://example.com/some.php?var1=1&var2=2
etc.

I have the following php code working in part:

preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/i', $content, $result, PREG_PATTERN_ORDER);

The only thing I need is ALSO capture urls with multiple query strings using "&" I get them, but not in full, I only receive things like:

http://example.com/asdad.php?var1=1&

The left is lost.

Can someone help me adding the part lost to the pattern?

Thanks so much in advance.


Solution

  • Well. Finally I got it:

    The final regex code is:

    $regex = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
    

    It works.