PHP Code

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

39 Comments

  1. 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. this works great. thanks!

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

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

  5. 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. Worked fine with 200 characters, thanks!

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

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

  9. 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. hi thanks i am looking this ratther than substr thanks once again

  11. Thanks! Works really great, that's exactly what I needed 😀

  12. 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. Hi, thanks for this. exactly what I needed right now

  14. A very handy function indeed, thanks!

  15. 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. 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. 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. Webdesign Berlin

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

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

  19. hi.

    a very handy script there.
    but, i'm wondering, if u could give me some advice on cutting a very loong WORD?

    i'm not too good in explanation. but, if i'm to give an example, the long word is like this:

    LotsofapplicationsrequireausertoinputaURLandlotsofproblemsoccurasaresult.IwasrecentlylookingforsomethingthatwouldtakeaURLasaninputandallowmetomakesurethatiswasformattedproperly.Therewasn’tanythingthatdidthissoIdecidedtowriteitmyself.

    it is as a sentence is written without whitespaces, making it only one word. And, it makes the layout, which i used stretches greater than my width limit.

    do u have any suggestion about my problem?

    thanks anyway. do reply to me if u have any suggestion. thanks! 🙂

  20. Thanks for this cool bit of simple php Justin, its really useful, especially now your post is up top of google too, don't need to bookmark anymore!

  21. [PHP] Shortening Text from DB

    […] 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.) […]

  22. 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;
    }
    }

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

    Thanks

  24. Never had a chance to say thanks before!
    i've been using this a couple of times for a couple of my site, thx!

  25. Pneumonic on "[Plugin: Category Page] Putting excerpts into pages" - Rurykster

    […] got that code from here so I take no credit for it, I just use it because it works. Now save your functions.php file and […]

  26. Hello!

    Very useful function, but words are broken when meeting special characters like 'È›' or 'È™'.

    Any ideas?
    Thanks!

  27. This is exactly what I wanted and it works perfectly! So easy to use! Thanks for the code!!

  28. Pneumonic on "[Plugin: Category Page] Putting excerpts into pages" | Rurykster.com

    […] got that code from here so I take no credit for it, I just use it because it works. Now save your functions.php file and […]

  29. Wanted to say thanks publicly since I've been linked on here twice in the comments. 🙂 I've used this quite a few times with a few modifications.

    Constantin: I just tried it with my revisions and it seems to work fine. Here's the code if it'll help:

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

    You can also use it for wordpress excerpts and stuff and add in some formatting:

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

    HTH someone.

  30. Not working for polish alphabet or other special chars ;/

  31. Thanks Justin … With the exception of the length, I did not have to play with your code at all!

  32. Good one Johnny (jan 25, 2010) – this handles times when you have a really long word and cuts it off before displaying the long work – not like the initial function

  33. Thnaks, works like a charm.

  34. HangoverPictures.com

    Works perfect for our site to manipulate user comments in the profile stalker wall area. nice job!

  35. I was trying for similar function, my search is over. Words are not enough to thank you, but still thank youuuuuuuuuuu……

  36. awesome script, use it for my CMS custome module,

    thanks..

  37. its 2011 folks..it still solved a lot of problems i was facing, thanks a lot..:D

  38. Does anyone know how to tie this into wordpress?

  39. PHP Trim String by Characters | PHP Neat Trim | XML Sitemap Blog

    […] So earlier today I needed a quick way of trimming a long description on a product to look like a short description, after a quick google search I came across this handy script from Justin Cook […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*
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.
Anti-spam image