Shorten a text string

This piece of code shortens a text string to the specified length on a word basis and adds “…” after. Perfect for use in teasers of lengthy text pieces and so on.

<?php
/**
* Shortens a string to the specified number of characters on a word basis.
* Adds "..." to the end of the string if the string was longer than specified.
* Example 1
* $text = "The sky is not the limit, I know 'cause I feel higher today!";
* echo shortenText($text);
*
* Would print:
* The sky is not the limit, I know 'cause I feel higher today!
*
* Example 2
* $text = "The sky is not the limit, I know 'cause I feel higher today!";
* echo shortenText($text, 20);
*
* Would print:
* The sky is not the...
*/
function shortenText($text, $chars = 256)
{
    // Do not shorten if the text is already
    // shorter that the desired amount.
    if(strlen($text) <= $chars)
        return $text;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";

    return $text;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>