Php Shorten a text string

Shorten a text string

Submitted by Totally PHP, 9th February 2004
Description

Function to shorten / truncate a string of text into a specific number of characters and add three dots (...) to the end. This will also round the text to the nearest whole word instead of cutting off part way through a word.
The code





/**

* Add this to your page:

*
* include "shorten_a_text_string.php";

* echo ShortenText($text);

* ?>

* where $text is the text you want to shorten.

*

* Example

* Test it using this in a PHP page:

*
* include "shortentext.php";

* $text = "The rain in Spain falls mainly on the plain.";

* echo ShortenText($text);

* ?>

*/



function ShortenText($text) {



// Change to the number of characters you want to display

$chars = 25;



$text = $text." ";

$text = substr($text,0,$chars);

$text = substr($text,0,strrpos($text,' '));

$text = $text."...";



return $text;



}



?>

Posted in |