Well here is my first so Labs post.
Often times, there are fields on forms or on pages that need to fit in a certain length. Article previews and select lists are two good examples. An easy way to ensure your text is withing the required length using PHP is to use $string = substr($string, 0, $length);. This has a number of disadvantages. Firstly, words can be cut at the end so you could end up with mixed meaning. For example, consider if the string "I hate sextants" was trimmed at 10 characters...you could end up with angry clients.
There is no built in PHP function to intelligently trim strings, so I wrote one. This function ensures strings are no longer than a maximum length and shows ellipses if trimming has occured. The function can be set to trim the string at the end, or to trim in the middle. (note: both of these trimming options assume left-to-right text, if someone wants to adapt the function for right-to-left languages feel free) In either case, the function tries its hardest not to cut any words in half.
Comments
Fantasy Football - June 16, 2004 8:45 pm
Thanks for the code! I used it on the front page of my fantasy football site. It displays the most recent forum topics in the top right corner, and sometimes the forum subject is too long, so it needs to be trimmed. Thanks again.
Fantasy Football - June 16, 2004 8:50 pm
By the way, is there an easy way to modify this code so that it trims characters instead of words? For example, right now "Are you ready for some football?" is trimmed to "Are you ready for some..." Is there an easy way to change the code so it would trim it to something like "Are your ready for some foo..."? Thanks!
Isaac Grant - June 17, 2004 12:31 pm
<p>If you're looking to just trim a string based on length with no intelligence, just use built-in php functions - like the following:</p>
<p>echo substr($string, 0, $length),'...';</p>
<p>where $string is the original string, and $length is the maximum you want it to take.</p>
Ian MacLeod - July 21, 2004 3:39 am
you could also do an additional check to see if the '...' is required (for the "unintelligent" trim)
$trimmed = substr($string, 0, $length);
if ($trimmed != $string)
$trimmed .= "...";
BoB - July 23, 2004 6:37 am
I wrote something like this myself, but the problems occure if your text contains htmlcode.
For example:
I like <a href="http://bobsworld.be">BoB's World</a>!
And you would cut the string at length 20 (with smartparsing) you get:
I like <a
Not something you want! Anybody an idea's to fix this?
David Chien - July 24, 2004 5:37 pm
<a href="#reply20911">BoB</a>, I think the best solution for that would be to actually remove all HTML tags (using strip_tags) from your source text prior to running it through this script.
Mike Gauthier - July 26, 2004 10:49 pm
BoB, On our intranet software, we actually filter out HTML tags and convert block level tags to newlines before running the smart trim. After we run the smart trim, we replace the newlines with bullet characters. This produces a very nice text summary sans HTML.
If you want to include HTML tags in the summarized code, I'd suggest writing a function which remembers the position of each filtered out HTML tag and reinserts them after running the smart trim. This would be a fairly complicated function.
Nick Zadrozny - August 28, 2004 2:55 am
To remember HTML with unintelligent trimming might be "fairly complicated" but it doesn't seem that bad. I have an idea that works in three steps:
1. generate trimmed string (unintelligently, in this case)
2. iterate to find corresponding end of original string (skip over tags, and remember them with a stack)
3. create a new resulting string (copy substring, add ellipse, close tags)
I don't know PHP but hacked up my closest imitation of that algorithm at http://zadrozny.com/nick/etc/php/trim-with-html.txt
Some obvious flaws in cases unaccounted-for, but, hey, it's a Friday night and what am I doing at the computer anyway? ;-)
Pablo Impallari - September 9, 2004 2:51 pm
Excelente script. I will put it to work in my projects right now.
congratulations.
john brown - September 16, 2004 12:28 am
Just a suggestion - if you do have to trim text embed it in a <span> with a title attribute that contains the full text - very helpful when your max length is relatively small and users will realize "oh, ellipses!" - and begin to mouseover to get more info...
Great site btw...
john brown - September 16, 2004 12:29 am
[doh]
"... embed it in a SPAN tag ..."
Julia - October 6, 2004 8:04 pm
I think that you must exclude dashes ? ex "quarter-mile" one word ! what do you think?
Kyle - October 24, 2004 4:53 pm
cf. Smarty's truncate function:
http://smarty.php.net/manual/en/language.modifier.truncate.php
Mike Gauthier - November 5, 2004 3:51 pm
Nick Zadrozny:
Inspired by my above statement that it would be hard to do, I wrote a function that removes HTML tags from a string and saves them in an associative array. A separate function re-inserts the elements in the correct places again.
These functions work great, but I never got around to adding them to the trimming functions (intelligent or unintelligent).
If you like, I'll post the code for them.
Rudolph The Reindeer - December 16, 2004 2:07 am
Here's another variation i found, but a bit simpler, doesnt include the ... but thats easy to do..
function smart_text ($content[string], $text_length[int])
{
$strip_content=stripslashes($content);
$all_content=strlen("$strip_content");
$standard_content=substr($strip_content ,$text_length);
$compare=stristr($standard_content ," ");
$minus_content=strlen("$compare");
$result_content=$all_content-$minus_content;
$display_content=substr($strip_content ,0, $result_content);
$striped_content=stripslashes($display_content);
echo nl2br($striped_content);
}
mohamed Elsharif - December 16, 2004 2:58 pm
Dear Sir,
I am tring to use the script on arabic language, it seem that the script on handle english characters. is there a way we can tell php what kind of characters to handle. my page is in arabic windows encoding. the script works in english but not the out out but is arabic.
thanks
karma - January 5, 2005 5:51 am
Folks,
I definately appreciate the hard work done....the "trim" script is cool... well am bit puzzled when i went through the codings.
My side....i have a 4 rows table each contents retrived from MySql Database.... so when i retrive it the whole data comes in the row...i dont want all story so i wanted to trim it just make it look cool and short to give hyperlink to the more page.
can any one tell how to do this or is there any easy way to trim ?
jon lampley - January 5, 2005 3:43 pm
Mike:
I'm interested in the additional code that re-inserts html tags into summarized text. Would you be willing to post / send it?
zava - January 6, 2005 2:50 pm
grat code...tx
Jason Clawson - April 27, 2005 4:01 pm
For those wanting to trim html content:
You shouldn't ever need to trim a string with html content in it. Consider further abstracting your meta data in the database. Also you should move any html to your template... assuming you are using a template engine... (if you aren't you should at least separate your presentation logic from business logic) Anyhow, you should only store data in the database not presentation markup. The template can handle the string trimming since that is presentation logic.
For example:
:::: mypage.php: ::::
$links = array();
$links[0] = array(
'url'=>'http://www.google.com',
'label'=>'Google Rocks',
);
//add more links here
//this isn't good programming style but it serves its purpose
include('mytemplate.php');
:::: mytemplate.php: ::::
<?php
foreach($links as $link):
?>
<a href="<?=$link['url']?>"><?=smart_trim($link['label'],6)?></a><br>
<?php
endforeach;
?>
:::: results in ::::
Google<br>
If you try and keep your presentation logic separate you will never run into problems like that.
ClauÃio - April 30, 2005 7:57 pm
pretty good code. i ll just paste it into a news page.
Chris - May 31, 2005 4:31 pm
Excellent little function...thx much
David - August 3, 2005 4:12 pm
Unbelievable.....I will try it on my Site tonight!
Bill Van Loo - November 26, 2005 11:32 pm
Thanks for making this available - I'm going to be using it in an updated version of my small label's site.
http://www.chromedecay.org/
thanks,
bvl
Ben - March 8, 2006 3:17 pm
Very nice, thank you.
rck - March 15, 2006 11:59 am
Hello Jason, in theory, you are of course right about not including html code in the first place. But thinking of actual, real-world applications like e.g. my site I must disagree. Take for example a blog or a forum. It has tons of links in text, doesn't it? Even if you abstract the HTML as bbcode, you still end up having controlling tags that can go bananas if cut unappropriately.
Been there, done that.
strip_tags seems to be a very good solution to use this script for e.g. presenting snippets of forum postings, etc. and is welcome in my toolkit of php snippets.
René C. Kiesler.
Scott Meinzer - March 30, 2006 11:42 pm
I actually think a way easier solution is the css text-overflow:ellipsis; option. This also allows your text length to resize if your site fills the browser window.
Rob - May 1, 2006 12:27 pm
"I actually think a way easier solution is the css text-overflow:ellipsis; option. This also allows your text length to resize if your site fills the browser window."
Yes, because only having it work with IE users is easier ;)
Mike Gauthier - February 4, 2007 1:43 am
For those interested, there is a more up to date and better documented version of this function available in SwatString as part of silverorange's Swat platform.