PHP: Trim a String Without Cutting Any Words

by admin on July 24, 2009 · 0 comments

I previously posted a function that allows you to trim a string in ASP without chopping any words in half. It works by trimming to the space nearest the desired string length. Here's the duplicate function in PHP.

It's called neat_trim.

/**
 * Cut string to n symbols and add delim but do not break words.
 *
 * Example:
 * <code>
 *  $string = 'this sentence is way too long';
 *  echo neat_trim($string, 16);
 * </code>
 *
 * Output: 'this sentence is…'
 *
 * @access public
 * @param string string we are operating with
 * @param integer character count to cut to
 * @param string|NULL delimiter. Default: '…'
 * @return string processed string
 **/

function neat_trim($str, $n, $delim='…') {
   $len = strlen($str);
   if ($len > $n) {
       preg_match('/(.{' . $n . '}.*?)b/', $str, $matches);
       return rtrim($matches[1]) . $delim;
   }
   else {
       return $str;
   }
}

Previous post:

Next post: