Truncate long text with PHP (excerpt function)
Jon Moffet
Truncate is a handy function which can truncate a long text into specific length string and adds elipsis (...) after it.
This is an example of how the function "truncate($text,47)" works :
Before
CODE:
-
This is a very long text that I type as an example to show you the functionality of truncate
After
CODE:
-
This is a very long text that I type as an exam....
Here's the PHP code that can let you do just that :
PHP:
-
function truncate ($str, $length=10, $trailing='...')
-
{
-
/*
-
** $str -String to truncate
-
** $length - length to truncate
-
** $trailing - the trailing character, default: "..."
-
*/
-
// take off chars for the trailing
-
{
-
// string exceeded length, truncate and add trailing dots
-
}
-
else
-
{
-
// string was already short enough, return the string
-
$res = $str;
-
}
-
-
return $res;
-
-
}
Truncate as an excerpt function
Truncate can be use to create excerpts from a very long text to serve as a preview or summary on your PHP application.
Tags: php, truncate, shorten, example, code, phpcode, tutorial
Posted in Uncategorized |








September 24th, 2008 at 12:37 pm
February 27th, 2009 at 5:51 pm
What if i want the text truncated at first ’space’ character after the number i give it, so that i evoid words being cut. Have you got a solution for this? Thanks
March 5th, 2009 at 4:35 am
http://news-world.us/pics
July 20th, 2009 at 5:01 am
If there’s html in the text, things could go south very quickly.
August 4th, 2009 at 8:23 am
Thanks for this tip..
I spent the whole day thinking of how to implement this functionality and was lucky to stumble on your tip.
Thanks for sharing :)
August 10th, 2009 at 11:05 pm
November 8th, 2009 at 1:09 am
February 13th, 2010 at 1:00 am