Return to Snippet

Revision: 23413
at February 6, 2010 18:19 by tcmacdonald


Initial Code
/**
 * Truncate a string to a certain length if necessary,
 * optionally splitting in the middle of a word, and
 * appending the $etc string or inserting $etc into the middle.
 * @param string 
 * @param integer 
 * @param string 
 * @param boolean 
 * @param boolean 
 * @return string 
 */
function truncate($string, $length = 80, $etc = '...',$break_words = false, $middle = false) {
	if ($length == 0)
		return '';
	if (strlen($string) > $length) {
		$length -= min($length, strlen($etc));
		if (!$break_words && !$middle) {
			$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
		}
		if(!$middle) {
			return substr($string, 0, $length) . $etc;
		} else {
		return substr($string, 0, $length/2) . $etc . substr($string, -$length/2);
		}
	} else {
		return $string;
	}
}

Initial URL

                                

Initial Description

                                

Initial Title
Truncate a string

Initial Tags
php

Initial Language
PHP