Aftab Sultan

Talkin' Geek
Posts Tagged ‘whole word’

April 25th, 2010

A whole word trim function

No Comments, code, PHP, Web development, by sultanaf.

Recently while upgrading the templates for this site to make it more mobile friendly, I decided to trim the post content on the front page to limit it to only show the first 10 or so words of the post. Obviously the substr function in PHP won’t work since it will simply cut off the string at x characters and possibly cut off words. To my knowledge no such function exists in PHP so I wrote a function of my own with regex goodness. Heres the code: 1234567891011121314151617181920212223/* This function will trim a string to x characters and truncate to the last whole word. str is the string to be trimmed x is the number of characters postfix is the string to append to the end of the trimmed function */ function trim_to_word($str, $x,  $postfix=’…’) { $str_len = strlen($str); if ($str_len > $x) { # Modify this line to customize the matching criteria $r = ‘/(.{‘ . $x . ‘}.*?)\b/’ preg_match($r, $str, $matches); # Trim the right side of the matched string and append the postfix return rtrim($matches[1]) . $postfix; } else { return $str; } }