shorten text but only cut on word boundaries

Permalink 1 user found helpful
When building a recent project I was a bit annoyed that shortened descriptions were cut off in the middle of words, so I added a customized shortText helper function that cuts the text only at word boudaries.
function shortText($textStr, $numChars=255, $tail='…') {
      if (intval($numChars)==0) $numChars=255;
      $textStr=strip_tags($textStr);
      if (mb_strlen($textStr) > $numChars) {
         $textStr=preg_replace('/\s+?(\S+)?$/', '', mb_substr($textStr, 0, $numChars)) . $tail;
      }
      return $textStr;            
   }

I'm just posting it here so other people who need this funcionality can also use it. Maybe this should even go into the core as standard behaviour?

PatrickHeck
 
12345j replied on at Permalink Reply
12345j
I'd add a github pull as a new function- maybe shortTextWord()
PatrickHeck replied on at Permalink Reply
PatrickHeck
Thanks J - just did that.
PatrickHeck replied on at Permalink Best Answer Reply
PatrickHeck
The function is in the core now and is called shortenTextWord()