Skip to content

Instantly share code, notes, and snippets.

@gbasov
Created September 29, 2012 15:11
Show Gist options
  • Save gbasov/3804294 to your computer and use it in GitHub Desktop.
Save gbasov/3804294 to your computer and use it in GitHub Desktop.
Convert urls to links
function url_to_link($text)
{
$text = preg_replace("@\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\@&=+$,%#-]+)*/?)@", '<a href="\0" target="_blank">\0</a>', $text);
$text = preg_replace("/href=\"([0-9a-zA-Z_\-]+\.)/U", 'href="http://$1', $text);
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment