silverorange labs

Comments

Comments are locked. No additional comments may be posted.

Fantasy Football -

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 -

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 -

<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 -

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 -

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 -

<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 -

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 -

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 -

Excelente script. I will put it to work in my projects right now.
congratulations.

john brown -

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 -

[doh]
"... embed it in a SPAN tag ..."

Julia -

I think that you must exclude dashes ? ex "quarter-mile" one word ! what do you think?

Kyle -

cf. Smarty's truncate function:

http://smarty.php.net/manual/en/language.modifier.truncate.php

Mike Gauthier -

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 -

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 -

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 -

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 -

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 -

grat code...tx

Jason Clawson -

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 -

pretty good code. i ll just paste it into a news page.

Chris -

Excellent little function...thx much

David -

Unbelievable.....I will try it on my Site tonight!

Bill Van Loo -

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 -

Very nice, thank you.

rck -

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 -

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 -

"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 -

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.

Pradeep Singh -

Friends use this code....it works

function limit_text($text, $limit) {
if (strlen($text) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}

Mike Gauthier -

Pradeep,

That function will work but doesn't do what the function I posted is supposed to do. For example, if the sentence being ellipsized uses really long words or really short words, your function will produce strange results.