Created
April 7, 2011 11:27
-
-
Save ecentinela/907604 to your computer and use it in GitHub Desktop.
Creates links for urls on text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function auto_link_text($text) { | |
$regexp = '/ | |
( # leading text | |
<\w+.*?>| # leading HTML tag, or | |
[^=!:\'"\/]| # leading punctuation, or | |
^ # beginning of line | |
) | |
( | |
(?:https?:\/\/)| # protocol spec, or | |
(?:www\.) # www.* | |
) | |
( | |
[-\w]+ # subdomain or domain | |
(?:\.[-\w]+)* # remaining subdomains or domain | |
(?::\d+)? # port | |
(?:\/(?:(?:[~\w\+%-]|(?:[,.;:][^\s$]))+)?)* # path | |
(?:\?[\w\+%&=.;-]+)? # query string | |
(?:\#[\w\-]*)? # trailing anchor | |
) | |
([[:punct:]]|\s|<|$) # trailing text | |
/x'; | |
return preg_replace_callback($regexp, function($matched) { | |
list($all, $before, $protocol, $address, $after) = $matched; | |
// already linked | |
if (preg_match('/<a\s/i', $before)) { | |
return $all; | |
} | |
$text = $protocol . $address; | |
$protocol = $protocol == 'www.' ? 'http://www.' : $protocol; | |
return "$before<a href=\"$protocol$address\">$text</a>$after"; | |
}, $text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment