note 55856 deleted from function.preg-replace by colder
| From: | colder@php.net | Date: | Mon, 18 Jun 2007 19:53:27 +0000 |
| Subject: | note 55856 deleted from function.preg-replace by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-127675@lists.php.net to get a copy of this message | ||
Note Submitter: urbanheroes {at} gmail {dot} com
----
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..."
?>