Search:
Main Menu
Login | RSS |

Quick PHP Code Tips and Examples

PHP Programming Tips, Tutorials and Source Code Examples for newbie

Truncate long text with PHP (excerpt function)

May 4th, 2007 by 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:
  1. This is a very long text that I type as an example to show you the functionality of truncate

After

CODE:
  1. 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:
  1. function truncate ($str, $length=10, $trailing='...')
  2. {
  3. /*
  4. ** $str -String to truncate
  5. ** $length - length to truncate
  6. ** $trailing - the trailing character, default: "..."
  7. */
  8.       // take off chars for the trailing
  9.       $length-=mb_strlen($trailing);
  10.       if (mb_strlen($str)> $length)
  11.       {
  12.          // string exceeded length, truncate and add trailing dots
  13.          return mb_substr($str,0,$length).$trailing;
  14.       }
  15.       else
  16.       {
  17.          // string was already short enough, return the string
  18.          $res = $str;
  19.       }
  20.  
  21.       return $res;
  22.  
  23. }

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: , , , , , ,

Bookmark Post:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • NewsVine
  • Reddit
  • Netvouz
  • Spurl
  • Furl
  • digg
  • YahooMyWeb
  • del.icio.us

Posted in Uncategorized |

Related Posts

One Response

  1. how to truncate text in php - Dogpile Web Search Says:

    Kramer auto Pingback[...] http://www.the-art-of-web.com/php/truncate/ • Found on Google, Windows Live, Yahoo! Search Truncate long text with PHP (excerpt function) » Quick PHP Code … Truncate as an excerpt function Truncate can be use to create excerpts from a very long text to [...]

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.