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!
- September 3, 2008
- article by Gabriel C.
- 2 comments
Related Posts
-
How to emphasize specific words from a string (text)at September 6, 2008
-
PHP: How to extract numbers from a string (text)at October 5, 2008 with 7 comments
-
PHP: Match Non-Alphanumeric Characters from a Stringat October 5, 2008
-
Format text into a SEO Friendly Stringat August 28, 2008 with 2 comments
-
PHP: Randomize Text Letters while Keeping the Words Readableat October 4, 2008 with 3 comments

2 Replies to "Shorten a string (text)"
September 5, 2008 at 8:12 AM
nice job…
October 30, 2008 at 11:17 PM
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; }