Truncate Text In PHP the Easy Way

Whilst looking for a way to truncate text in my content manager I thought about the best way to approach this. To begin with I thought it might be a good idea to use a method written into a class like this:

//truncate text
public function truncate($text) {
//specify number fo characters to shorten by
$chars = 25;
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
return $text;
}

There is nothing wrong with this method, it serves its purpose, however I wanted to find a quicker and easier way to apply truncation whereby I could define the number of characters to truncate by. ThisĀ  could be written into the arguments passed to the truncate function, however this is still what I would call ‘code heavy’ After a bit of thinking I found this to be a much more suitable solution to the problem.

<?php $someText = 'this is textthis is textthis is textthis is textthis is text'?>
<?php echo(substr($someText, 0,25)).'...'; ?>

This simple use of the substr() function built into PHP and saves a lot of the method hassle. I hope this proves useful if you find yourself in the same situation.

  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • Google Bookmarks
  • email
  • Facebook
  • RSS

One Response to “Truncate Text In PHP the Easy Way”

  1. Gordon

    brilliant. so simple an easy to implement, will be using this right away!

    « Reply


Talk to me