Skip to content

Instantly share code, notes, and snippets.

@bytespider
Created March 11, 2015 20:41
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 bytespider/c45e5fe4b4fb4ae0cd54 to your computer and use it in GitHub Desktop.
Save bytespider/c45e5fe4b4fb4ae0cd54 to your computer and use it in GitHub Desktop.
public function autoLinkText($text)
{
// a more readably-formatted version of the pattern is on http://daringfireball.net/2010/07/improved_regex_for_matching_urls
$pattern = '/((https?):\/\/)?([\da-z\.-]+\.[a-z\.]+)([\/\w \.-]+)*\/?/i';
$callback = function($matches) {
$url = array_shift($matches);
if (is_null(parse_url($url, PHP_URL_SCHEME))) {
$url = 'http://' . $url;
}
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
return sprintf('<a rel="nofollow" href="%s">%s</a>', $url, $text);
};
return preg_replace_callback($pattern, $callback, $text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment