Skip to content

Instantly share code, notes, and snippets.

@heyost
Created June 30, 2016 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heyost/e707ce866e9e5c9ace2a008103316e20 to your computer and use it in GitHub Desktop.
Save heyost/e707ce866e9e5c9ace2a008103316e20 to your computer and use it in GitHub Desktop.
Regex clickable URL from plain string
function clickable_url($plain_text)
{
// check all url with http:// pattern
$pattern_http = '~([^<>]*>)(*SKIP)(*F)|'; // skip url check if inside html tag
$pattern_http .= '([-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z])(*SKIP)(*F)|'; // skip email pattern
$pattern_http .= '(?:(?:ht|f)tps?://)'; // find url with http | https | ftp | ftps
$pattern_http .= '[\w-]+'; // host name
$pattern_http .= '(?:\.[\w-]+)+'; // domain name
$pattern_http .= '[\w-.,@?^=%&:/\~+#!]*[\w-@?^=%&/\~+#]~xiuS'; // path name
$result = preg_replace($pattern_http, '<a href="$0" target="_blank">$0</a>', $plain_text);
// check all url without http:// pattern
$pattern = '~([^<>]*>)(*SKIP)(*F)|'; // skip url check if inside html tag
$pattern .= '([-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z])(*SKIP)(*F)|'; // skip email pattern
$pattern .= '(?:(?:ht|f)tps?://)[\w-]+'; // skip url with http | https | ftp | ftps
$pattern .= '(?:\.[\w-]+)+';
$pattern .= '[\w-.,@?^=%&:/\~+#!]*[\w-@?^=%&/\~+#](*SKIP)(*F)|';
$pattern .= '(|(?:(?:ht|f)tps?://|www\.))'; // find url without http | https | ftp | ftps
$pattern .= '[\w-]+'; // host name
$pattern .= '(?:\.[\w-]+)+'; // domain name
$pattern .= '[\w-.,@?^=%&:/\~+#!]*[\w-@?^=%&/\~+#]~xiuS'; // path name
$result = preg_replace($pattern, '<a href="http://$0" target="_blank">$0</a>', $result);
// Double check regex because sometime there have URL without www or http when change to html href, browser detect there is url part of parent url
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment