Phrase Truncation Function in PHP

Here is a handy little helper function that will truncate a string to the word closest to the set limit (in other words, it won’t truncate in the middle of a word). Even though it’s pretty simple, I’ve already used it in a few projects, so I thought it would be worth sharing. Feel free to improve it and/or rip it apart. If you see a change to be made, let me know by leaving a comment.

function truncate_str($string, $limit)
{
	if (strlen($string) <= $limit)
	{
		$string = $string; // Do nothing
	}
 	else
	{
		$string = wordwrap($string, $limit);
		$string = substr($string, 0, strpos($string, "\n"));
		$string .= "...";
	}
	return $string;
}

Update: Here’s an updated, condensed version of the above code.  It shortens the function and gets rid of some redundant lines (i.e., $string = $string).

function truncate_str($string, $limit)
{
    if (strlen($string) > $limit)
    {
    	$string = wordwrap($string, $limit);
      	$string = substr($string, 0, strpos($string, "\n"));
      	$string .= "...";
    }
    return $string;
}

Latest Photos on flickr

Anastasia, December 2011 Sirius over East Grand Satellite Flare Capitol Lights Anastasia, February 2011, pt. 6 Anastasia, February 2011, pt. 5


Recently Played Tunes

Best of Traffic
Traffic
Plans
Death Cab for Cutie
February 22, 2012 at 10:33 pm
City Of Black & White
Mat Kearney
February 22, 2012 at 10:23 pm


Blog Archives

2011 01 02 03 04 05 06 07 08 09 10 11 12
2010 01 02 03 04 05 06 07 08 09 10 11 12
2009 01 02 03 04 05 06 07 08 09 10 11 12


Favorites on the Web

full of awesome design inspiration
where I fulfill my typophile desires
the best graphic design community on the web