Skip to content

Instantly share code, notes, and snippets.

@AlexPashley
Last active January 25, 2023 23:40
Show Gist options
  • Save AlexPashley/5861213 to your computer and use it in GitHub Desktop.
Save AlexPashley/5861213 to your computer and use it in GitHub Desktop.
PHP: function that will replace textual URLs with HTML links, this also works for email addresses.
<?php
function replace_links( $text )
{
$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
$ret = ' ' . $text;
// Replace Links with http://
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);
// Replace Links without http://
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);
// Replace Email Addresses
$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
$ret = substr($ret, 1);
return $ret;
}
@frkinta
Copy link

frkinta commented Aug 3, 2019

Thank you

@xastrix
Copy link

xastrix commented Apr 16, 2022

just what me need, thank you

@alejandropvwbtc
Copy link

Gracias!

@hsmfawaz
Copy link

Thanks so much

@lekiend
Copy link

lekiend commented Jan 18, 2023

Thank you, nice but some urls without http(s) and without www are not identified as links.
Example: georisques.gouv.fr

Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment