Regex and PHP: adding ellipsis after X number of chars
Should be fairly simple for someone who knows regex. I am unfortunately not among those in the know.
How can one append ellipsis to anything over 27 chars in the below example, so that the fourth link listed will appear as http://iamanextremely.com/long/lin
?
<?php
$input = <<<EOF
http://www.example.com/
http://example.com
www.example.com
http://iamanextremely.com/long/link/so/I/will/be/trimmed/down/a/bit/so/i/dont/mess/up/text/wrapping.html
EOF;
$outpu开发者_JS百科t = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,27})[^(\s|,)<]*)/",
'<a href="http://$2$3" rel="nofollow">http://$2$4</a>', $input);
You could use preg_replace_callback
to apply a callback to all matched urls. In the callback you can make stuff as fancy as you wish.
$output = preg_replace_callback('#(http://|www\\.)[^\\s<]+[^\\s<,.]#i',
'trimlong',$input);
function trimlong($match)
{
$url = $match[0];
$disp = $url;
if ( strlen($disp) > 24 ) $disp = substr($disp,0,24)."...";
return "<a href=\"$url\">$disp</a>";
}
(ps. I just took your regexp to start with, I don't think matching a url should be that cumbersome.)
Unless you need to match a specific format, i.e. only the http:// links, a regex is overkill. Just use string functions and loop over your urls testing their length. If you want to get fancy, use explode()
and array_walk()
if (strlen($url) > 27) {
echo substr($url, 0, 27) . '...';
}
else {
echo $url;
}
If this is for display in an HTML page, you might consider using CSS to style it with an ellipsis rather than manually truncating it.
You would use CSS something like this:
.cutshort {
overflow: hidden;
-o-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
width:100%;
}
The text would then be truncated on screen and be given an ellipsis, even though the HTML code contained the full string.
This technique is not suited to all cases, but where it works it is an excellent alternative to hacking around with your content before sending it to the user.
One important note: The current version of Firefox browser doesn't display the ellipsis dots. It does still truncate correctly though, so it's not a disaster. All other browsers do show the dots, and hopefully a new version of firefox due soon will add it too.
精彩评论