PHP: Regular expression to make linkable url in string

February 16, 2011 | In: php, Regular Expression, web development

Are you looking for a regular expression to make clickable url in the string? Yes!, you will get your solutions here:

 
echo preg_replace("/http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", "<a href=\"$0\">$0</a>", $string);

If you want to open url in new tab then :

 
echo preg_replace("/http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", "<a href=\"$0\" target='_blank'>$0</a>", $string);