note 30871 deleted from ref.strings by tomsommer

From: Date: Wed, 15 Sep 2004 20:48:02 +0000
Subject: note 30871 deleted from ref.strings by tomsommer
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-76788@lists.php.net to get a copy of this message
Note Submitter: szeryf at negativeIQ dot pl ---- This is a little function I wrote for shortening strings to some arbitrary length. It may be useful if you want to display only headlines (or just a few starting sequences) of a larger text. The text is shortened to the last white space character before $len chars and an ellipsis (...) is added at the end. If no white space is found, the first $len chars (and ...) are returned. So the maximal length of returned value is always $len + 3. Here it goes: function shorten ($var, $len = 120) { if (empty ($var)) { return ""; } if (strlen ($var) < $len) { return $var; } if (preg_match ("/(.{1,$len})\s/", $var, $match)) { return $match [1] . "..."; } else { return substr ($var, 0, $len) . "..."; } } It should be pretty self-explanatory. The regular expression matches up to $len chars followed by a white space char (\s). The match is "greedy", so it always tries to match "as many as possible".

« previous php.notes (#76788) next »