note 55856 added to function.preg-replace
| From: | urbanheroes{at}gmail{dot}com at osu1 dot php dot net | Date: | Mon, 15 Aug 2005 20:00:57 +0000 |
| Subject: | note 55856 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-93696@lists.php.net to get a copy of this message | ||
Here are two functions to trim a string down to a certain size.
"wordLimit" trims a string down to a certain number of words, and adds an ellipsis after
the last word, or returns the string if the limit is larger than the number of words in the string.
"stringLimit" trims a string down to a certain number of characters, and adds an ellipsis
after the last word, without truncating any words in the middle (it will instead leave it out), or
returns the string if the limit is larger than the string size. The length of a string will INCLUDE
the length of the ellipsis.
<?php
function wordLimit($string, $length = 50, $ellipsis = '...') {
return count($words = preg_split('/\s+/', ltrim($string), $length + 1)) > $length ?
rtrim(substr($string, 0, strlen($string) - strlen(end($words)))) . $ellipsis :
$string;
}
function stringLimit($string, $length = 50, $ellipsis = '...') {
return strlen($fragment = substr($string, 0, $length + 1 - strlen($ellipsis))) <
strlen($string) + 1 ?
preg_replace('/\s*\S*$/', '', $fragment) . $ellipsis : $string;
}
echo wordLimit(' You can limit a string to only so many words.', 6);
// Output: "You can limit a string to..."
echo stringLimit('Or you can limit a string to a certain amount of characters.', 32);
// Output: "Or you can limit a string to..."
?>
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+55856
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55856&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55856&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55856&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55856&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55856&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55856&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+55856&report=yes
Search -- http://master.php.net/manage/user-notes.php