note 30871 added to ref.strings
| From: | szeryf at negativeIQ dot pl | Date: | Tue, 01 Apr 2003 19:41:11 +0000 |
| Subject: | note 30871 added to ref.strings | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-46090@lists.php.net to get a copy of this message | ||
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".
--
http://www.php.net/manual/en/ref.strings.php
http://master.php.net/manage/user-notes.php?action=edit+30871
http://master.php.net/manage/user-notes.php?action=delete+30871
http://master.php.net/manage/user-notes.php?action=reject+30871