Simple RegEx for matching URLs

I wanted a simple regular expression to retrieve URLs from a paragraph of text, but a google search returned so many Regular Expressions that it was tough to separate the good from the bad. So here are two tried and tested Perl Compatible Regular Expressions (PCRE) to help match URLs:

A simple one to match most ‘http’ based links:

(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)

and another more complex one which will match every Link/URL on the face of this planet


([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((news|telnet|nttp|file|http|ftp|https)://)
|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*[^]'\\.}>\\),\\\"]

I’ve got a simple PHP function to linkify any URL in a blob of text:

$re = '@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@'; 
$replacement = "<a href='$1'>$1</a>"; 
$formatted_text = preg_replace($re, $replacement, $text); 
echo $formatted_text;

Simple PHP. Any improvements, please post them in the comments.

Advertisement

One comment

  1. Aneeq · ·

    I have found a good solution on the site below. Works like charm for me.

    http://phphelp.co/2012/03/28/how-to-print-all-the-months-and-years-between-two-dates-in-php/

    Or

    http://addr.pk/ac8b

%d bloggers like this: