Adam Patterson

Regular Expression for URLs using ereg_replace


Posted in: Articles on August 20th, 2009

I had a heck of a time finding a Regular Expression to parse URLs in a body of text. The beauty with this expression is its flexibility, it will handle a http or https url with or without www. And it’s fine with tiny urls.

// $subject contains a body of text with non html URLs
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $subject);

This is posted more as a snippet because is spent so long trying to find one that would work.

$subject will be the body of text containing flat text urls. $text will now contain our information.

// Output New formatted content with links.
echo $text;

Now our content is parsed with URLs.

Done!