Interested in purchasing one of the best wordpress themes in town? check out Cult on themeforest »

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.

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.


    About the author

    My name is Philip Beel. I have four years commercial experience in front end web development. My disciplines include XHTML, CSS, PHP, MYSQL, Smarty and javascript. I am also a keen advocate of the jQuery framework.

    Read more posts by


    3 Comments on Truncate Text In PHP the Easy Way

    1. Gordon

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

      « Reply


    2. web designing uae

      Easy to work out.Thanks for the share.

      « Reply


    3. Chris

      Very Nice. I used to hate truncating That was of course before I came across your script. Works like a dream. I’m going to be using this one for a lot of projects. Thanks for posting!

      « Reply


    Leave a comment


    This pretty much personifies me - http://t.co/glu8rD8j #cycling

    Follow me