PHP function to truncate text (into a preview or excerpt) with trailing dots…

by Marty on January 4, 2010

The following PHP function will output text as a preview – the same way WordPress delivers short excerpts for every post. Although it is customary to follow each excerpt with three dots, you can customise the trailing text by altering the $etc variable. Call this function by using ttruncat($text,$numb), where $text is the text you want to truncate, and $numb is the number of characters that you want to output.





<?php
function ttruncat($text,$numb) {
if (strlen($text) > $numb) {
  $text = substr($text, 0, $numb);
  $text = substr($text,0,strrpos($text," "));
  $etc = " ...";
  $text = $text.$etc;
  }
return $text;
}
?>
Share this page:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • Identi.ca
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • Twitter
  • Yahoo! Bookmarks

If you liked this article, you may also like:

  1. PHP function to generate random password string
  2. Make text links clickable
  3. PHP Function to Force Links to Open in a New Window
  4. A problem with the PHP mail function… and alternatives

Leave a Comment

Previous post:

Next post:

Get Adobe Flash playerPlugin by wpburn.com wordpress themes