Shorten a string (text)

Posted on September 3, 2008, under PHP,  Bookmark it

This is a function which shortens a text. For instance, this is useful when you want to display in a page excerpts from your articles (with the link to the full article).

<?php
function shorten_string($string, $chars, $end = '...', $strip_tags = true)
{
$string = ($strip_tags) ? strip_tags($string) : $string;
$str = substr($string, 0, $chars).$end;

return $str;
}

$text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Maecenas ac nulla at neque consectetuer semper.
Pellentesque et quam at justo rhoncus accumsan.
Nullam posuere, nisl eu porta dignissim, massa dolor porttitor mi,
at consequat mi ante in tortor.';

/*
1st argument: your text
2nd argument: how many chars to show from the string's beginning
3rd argument: the ending string (i.e. ... [more] [continue])
4th argument: Strip Tags (true or false)
*/

$excerpt = shorten_string($text, 100, '...[More]', true);

echo $excerpt;
?>

NOTE: The 3rd argument can be used as a link to your full article like: …<a href=”http://www.mydomain.com/article_page”>[More]</a>

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

2 Replies to "Shorten a string (text)"

  1. Here is a bit that strips to the nearest space!

    function shorten_string($string, $chars, $end = '...', $strip_tags = true)
    {
    $string = ($strip_tags) ? strip_tags($string) : $string;
    $str = substr($string, 0, $chars);
         if (substr_count($str," ") > 1) {
         $lastspace = strrpos($str," ");
         $str= substr($str,0,$lastspace);
    }
    
    return $str.$end;
    }
    

Leave a Reply


* = required fields

  (will not be published)


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

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)