Last active
October 10, 2015 16:18
-
-
Save steve-todorov/3717420 to your computer and use it in GitHub Desktop.
Replace links with html links.
This file contains hidden or 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
<?php | |
/** | |
* This function replaces all of the links in $text with with html links. | |
* | |
* @param string $text | |
* @param string $target ("_blank", "_self", "_parent", "_top", framename) | |
* | |
* @return string | |
*/ | |
function toLink( $text, $target = "" ) | |
{ | |
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#'; | |
$callback = function($matches) use ($target){ | |
$url = $matches[0]; | |
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH).(parse_url($url, PHP_URL_QUERY) ? "?".parse_url($url, PHP_URL_QUERY) : ""); | |
$text = preg_replace("/^www./", "", $text); | |
$last_slash = strpos($text, "/")+1; | |
if ($last_slash > 1) { | |
$text_length = strlen($text)-$last_slash; | |
if($text_length > 10) | |
$text = substr($text, 0, $last_slash+10) . "…"; | |
} | |
if($target == "") | |
return sprintf('<a rel="nofollow" href="%s">%s</a>', $url, $text); | |
else | |
return sprintf('<a rel="nofollow" href="%s" target="'.$target.'">%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