Aftab Sultan

Talkin' Geek
Posts Tagged ‘web development’

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

I recently had a chance to work with JQuery for a web development course. JQuery totally changed the way I think about JavaScript. The best part is the ease by which you can make AJAX calls. For those starting out with JQuery, this cheatsheet is a must have! For those who missed the xkcd fun on April Fool’s, you can still access the page here. After spending some time messing around with it trying to find the easter eggs, I ended up looking at the source code (kind of cheating, I know lol). With the beginning of summer, this means one and one thing only: StarCraft II.