note 70057 deleted from function.substr by bobby

From: Date: Mon, 02 Oct 2006 02:36:03 +0000
Subject: note 70057 deleted from function.substr by bobby
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-117921@lists.php.net to get a copy of this message
Note Submitter: feedback at realitymedias dot com ---- Here is a way to chop a string (long text to short text) without cutting it in the middle of a word but still based on total string lenght; It will try to make the string as close as $maxlen as possible - result will not be greater (in length) than $maxlen+$maxoverflow - If the next word to be injected exceed $maxoverflow, the final length will be smaller than $maxlen. $elli is used to append something to a chopped result (eg.: "...") strtrim("hello world, this is a string cutter!", 25, 15, "..."); function strtrim($str, $maxlen=100, $maxoverflow=15, $elli=NULL) { if (strlen($str) > $maxlen) { $output = NULL; $body = explode(" ", $str); $body_count = count($body); $i=0; do { $output .= $body[$i]." "; $thisLen = strlen($output); $cycle = ($thisLen < $maxlen && $i < $body_count-1 && ($thisLen+strlen($body[$i+1])) < $maxlen+$maxoverflow?true:false); $i++; } while ($cycle); return $output.$elli; } else return $str; } - Result should be: hello world, this is a sting ... - If the word "string" would have been longer than $maxlen, result would have been "hello world, this is a ..." - $elli is not appended if the string does not need to be cutted.

« previous php.notes (#117921) next »