note 92556 added to function.str-word-count
| From: | charliefrancis at gmail dot com | Date: | Wed, 29 Jul 2009 11:56:01 +0000 |
| Subject: | note 92556 added to function.str-word-count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158866@lists.php.net to get a copy of this message | ||
Hi this is the first time I have posted on the php manual, I hope some of you will like this little
function I wrote.
It returns a string with a certain character limit, but still retaining whole words.
It breaks out of the foreach loop once it has found a string short enough to display, and the
character list can be edited.
<?php
function word_limiter( $text, $limit = 30, $chars = '0123456789' ) {
if( strlen( $text ) > $limit ) {
$words = str_word_count( $text, 2, $chars );
$words = array_reverse( $words, TRUE );
foreach( $words as $length => $word ) {
if( $length + strlen( $word ) >= $limit ) {
array_shift( $words );
} else {
break;
}
}
$words = array_reverse( $words );
$text = implode( " ", $words ) . '…';
}
return $text;
}
$str = "Hello this is a list of words that is too long";
echo '1: ' . word_limiter( $str );
$str = "Hello this is a list of words";
echo '2: ' . word_limiter( $str );
?>
1: Hello this is a list of words…
2: Hello this is a list of words
----
Server IP: 64.71.164.2
Probable Submitter: 88.211.48.46
----
Manual Page -- http://www.php.net/manual/en/function.str-word-count.php
Edit -- https://master.php.net/note/edit/92556
Del: integrated -- https://master.php.net/note/delete/92556/integrated
Del: useless -- https://master.php.net/note/delete/92556/useless
Del: bad code -- https://master.php.net/note/delete/92556/bad+code
Del: spam -- https://master.php.net/note/delete/92556/spam
Del: non-english -- https://master.php.net/note/delete/92556/non-english
Del: in docs -- https://master.php.net/note/delete/92556/in+docs
Del: other reasons-- https://master.php.net/note/delete/92556
Reject -- https://master.php.net/note/reject/92556
Search -- https://master.php.net/manage/user-notes.php