June 27th, 2006

PHP: Trim a String Without Cutting Any Words

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;
   }
}
  • Share/Bookmark

21 Responses to ' PHP: Trim a String Without Cutting Any Words '

Subscribe to comments with RSS or TrackBack to ' PHP: Trim a String Without Cutting Any Words '.

  1. Andy Gibson said,

    on April 4th, 2007 at 5:16 am

    Very handy function that, I was asked to add a feature to the company news listings on our homepage that would only display the first 10 words of a new post, this did the trick with just one change:


    preg_match('/(.{' . $n . '}.*\s)\b/', $str, $matches);

    This makes the regex search for any whitespace and returns a match each time.

  2. johnny said,

    on June 22nd, 2007 at 5:50 pm

    this works great. thanks!

  3. had3z said,

    on August 8th, 2007 at 10:25 am

    johnny, i second that. one year after it's posted, it still helps a clueless dude :)

  4. Graham said,

    on August 21st, 2007 at 8:56 am

    And I second had3z! A year later, but still entirely useful.

  5. daz said,

    on October 21st, 2007 at 4:47 am

    this worked great for me, but when i wanted to trim more than 100 it did not work. Very new to php so can anyone help

  6. Andrea said,

    on October 24th, 2007 at 4:28 pm

    Worked fine with 200 characters, thanks!

  7. Diego said,

    on December 7th, 2007 at 1:20 pm

    Script works great! A friend told me that the programmers behind the Earthoid Search Engine use your script! Right On!

  8. Anon said,

    on January 8th, 2008 at 4:15 pm

    It's good, but the usage of regular expression here is superfluous. A simple substr function could better the script in so many ways :P Nice way to get the topic discussion going though.

  9. Rob said,

    on April 17th, 2008 at 2:38 pm

    Hi justin
    Thanks, this is a great script!
    I noticed that if the nearest space to the cut-off point is at the end of the string, then the '…' is still added at the end, even though the string hasn't been trimmed.
    I came up with this solution. It's probably not very good code, but it worked for me:

    $trStr = rtrim($matches[1]) . $delim;
    if(str_replace($delim,'',$trStr) == $str) $trStr = $str;
    return $trStr;

    replaces:

    return rtrim($matches[1]) . $delim;

    Just thought it might be useful to share :)

  10. Pawan said,

    on August 9th, 2008 at 4:00 am

    hi thanks i am looking this ratther than substr thanks once again

  11. Isaura said,

    on December 3rd, 2008 at 12:44 pm

    Thanks! Works really great, that's exactly what I needed :D

  12. Greg said,

    on December 16th, 2008 at 10:50 pm

    When using this with some CMS's I found that using a count of 200+ would return a blank string. To prevent this I had to remove any newline and carriage return characters. Also, I removed any tags as sometimes ending tags were removed from the trimmed version.

    I added this code before $len is set.

    $str = str_replace("\n","",$str);
    $str = str_replace("\r",",$str);
    $str = strip_tags($str);

    Thanks for the code!

  13. fedmich said,

    on December 29th, 2008 at 2:01 am

    Hi, thanks for this. exactly what I needed right now

  14. Kevin Godden said,

    on February 9th, 2009 at 8:05 am

    A very handy function indeed, thanks!

  15. Socket1 said,

    on March 15th, 2009 at 6:17 pm

    I replaced everything inside the if statement with this
    $length = $len-$n;
    return substr($str, 0, '-'.$length).$delim;

    and it works fine for me.

  16. Ulysses said,

    on March 25th, 2009 at 3:51 am

    I would definitely add Greg's extra code of removing carriage returns and breaks, as I was also having a problem of neat_trim occasionally returning nothing in Drupal…


  17. on April 9th, 2009 at 12:57 am

    Here's a different route without the use of preg_match simplified conditionals through assumptions.

    function truncate($string, $length, $break = ") {
    if (strlen($string) > $length) {
    $pos = strpos($string, " ", $length);
    return substr($string, 0, $pos) . $break;
    }

    return $string;
    }


  18. on April 15th, 2009 at 2:42 am

    Shorter, dont know its faster: (displaying 30 words from the begining of a string)

    implode(' ',array_slice(explode(' ',$string),0,30))


  19. on January 20th, 2010 at 6:40 am

    [...] PHP: Trim a String Without Cutting Any Words (I make no assertion about the licensing position for that snippet, check it yourself on the site.) [...]

  20. Jonny said,

    on January 25th, 2010 at 9:06 am

    Or you can use:

    function Cut($string, $max_length)
    {
    if (strlen($string) > $max_length)
    {
    $string = substr($string, 0, $max_length);
    $pos = strrpos($string, ” “);
    if($pos === false)
    {
    return substr($string, 0, $max_length).”…”;
    }
    return substr($string, 0, $pos).”…”;
    }
    else
    {
    return $string;
    }
    }


  21. on February 16th, 2010 at 8:48 am

    Great function mate. I will use this over and over again.

    Thanks

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word