When building websites I'm forever chopping up strings to make them display nicely as headings and paragraphs. I use the substr function to chop-off unwanted characters and then add in ellipses. For example:
if ( strlen ( $mystring ) > 22 ) {
echo substr( $mystring,0,21 ).'...';
} else {
echo $mystring;
}
This works pretty good most of the time, but it is far from perfect. Check out how the shortened headings look on one of my sites. You can clearly see a lot of inconsistency in how the shortened headings look.
Surel开发者_如何学Pythony, there is a better PHP method/ technique?
Your problem is that normal fonts are not monospaced, i.e. the various letters have different widths. Because PHP can't tell the final width of the resulting string in the browser, it is impossible to tell what position one needs to cut the string at.
There are jQuery based solutions for this (jQuery, running in the browser, does have access to the actual width information. @Dan shows a plugin in his answer); the downside of this of course is that it won't work without JavaScript.
If you want to invest the time, it would be possible to use GD's imagettfbbox()
to calculate the approximate boundary using a common font like Arial. That would be far from perfectly reliable, but should give you a rough idea where to apply the cut.
No, because PHP doesn't know anything about how the text is going to end up rendered in the browser. Other people aren't even seeing the same thing you are for the same HTML, so how can changing the HTML your PHP generates fix this?
The only way to get consistent length text is to do the adjustments on the client side.
Something like the jQUery Ellipsis plugin: http://plugins.jquery.com/plugin-tags/ellipsis
Edit: My bad, you want ellipsis... Your ellipses looks fine on that page you showed...
If you Really want them to line up you could put the text in an inline element with max width such and such and overflow: hidden
followed by a seperate element with the ellipsis.
Another way is play around with CSS. You don't cut your text (or you just shorten it a bit if it's very long) and then you place it in a fixed width container with overflow: hidden
. If you want the dots you can add another element containing them above the end of the text with position: absolute
.
精彩评论