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

No Comments

Leave a Reply