Try the following:
define( 'URL_REGEX', <<<'_END'
~(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""‘’]))~
_END
);
function replace_urls_with_anchor_tags( $string,
$length = 50,
$elision_string = '...' ) {
$replace_function = function( $matches ) use ( $length, $elision_string) {
$matched_url = $matches[ 0 ];
return '<a href="' . $matched_url . '">' .
abbreviated_url( $matched_url, $length, $elision_string ) .
'</a>';
};
return preg_replace_callback(
URL_REGEX,
$replace_function,
$string
);
}
function abbreviated_url( $url, $length = 50, $elision_string = '...' ) {
if ( strlen( $url ) <= $length ) {
return $url;
}
$width_either_side = (int) ( ( $length - strlen( $elision_string ) ) / 2 );
$left = substr( $url, 0, $width_either_side );
$right = substr( $url, strlen( $url ) - $width_either_side );
return $left . $elision_string . $right;
}
(The return in the URL_REGEX definition confuses the syntax highlighting of stackoverflow.com, but this is nothing to worry about)
The function replace_urls_with_anchor_tagstakes a string and changes all the URLs matching inside, to the tag binding, shortening the long URLs with ellipses with ellipses. The function accepts optional arguments lengthand elision_stringif you want to play with the length and change the ellipses to something else.
Here is a usage example:
$test = <<<_END
Look here:
http://www.rocketlanguages.com/spanish/resources/pronunciation_spanish_accents.php
And here:
http://stackoverflow.com/questions/12385770/implementing-web-address-regular-expression
_END;
echo replace_urls_with_anchor_tags( $test, 50, '...' );
: PHP 5.2 , replace_urls_with_anchor_tags, create_function . PHP 5.3:
function replace_urls_with_anchor_tags( $string,
$length = 50,
$elision_string = '...' ) {
$replace_function = create_function(
'$matches',
'return "<a href=\"$matches[0]\">" .
abbreviated_url( $matches[ 0 ], ' .
$length . ', ' .
'"' . $elision_string . '"' .
') . "</a>";'
);
return preg_replace_callback(
URL_REGEX,
$replace_function,
$string
);
}
, URL- regex, , DaveRandom, . , : "/" (: [\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#]). , , 80 8080.
, .