PHP substring without breaking a word

A while back I explained how you can use php substr function to truncate some text for a preview of a full listing. That method will cut your text right at 250 characters which may leave you with a word cut off right in the middle. Today I am going to show you a simple function that will keep all your words in tact but still allow you to shorten for preview.

The simple algorithm is as follows:

  1. Is the string longer than our limit ( in this case 250 )
  2. Truncate the string to our limit
  3. If we ended up in the middle of a word
  4. Trim out that broken word by finding the previous space

What this will do is take out the last word that gets broken apart by the truncation, this will give you less than 250 characters returned if it were to truncate right in the middle of a word. This is useful if you have a limited space you are working with and don't want to do the alternative option, to complete the full word that was broken, which would give you mroe than 250 characters.

The php to accomplish this is pretty simple

function truncate_str($str, $maxlen) {
if ( strlen($str) <= $maxlen ) return $str;

$newstr = substr($str, 0, $maxlen);
if ( substr($newstr,-1,1) != ' ' ) $newstr = substr($newstr, 0, strrpos($newstr, " "));

return $newstr;
}

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up