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

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;
}
?>

If you liked this article, you may also like:

  1. PHP function to generate random password string
  2. Make text links clickable
  3. Wrap a long string, word or URL over multiple lines with a PHP function
  4. PHP Function to Force Links to Open in a New Window
  5. A problem with the PHP mail function… and alternatives
About Marty

is a passionate web developer from Sydney, Australia. He owns about 400 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. You can follow Marty on Twitter or Google+.

Speak Your Mind

*