[nycphp-talk] strpos with space
Michael Sims
jellicle at gmail.com
Mon Jul 25 16:01:28 EDT 2005
On Monday 25 July 2005 14:41, Brian O'Connor wrote:
> Here is the function, maybe I am misunderstanding something:
>
> function createTextPreview($text, $words = 250)
> {
> if(str_word_count($text) < $words) {
> return $text;
> } else {
> return substr($text, 0, strpos($text, ' ', $words)) . ' ... [ <a
> href="link">full text</a> ]' . str_word_count($text);
Note that str_word_count($foo) returns the number of words found, with
no indication of anything else (such as where the 250th word might be).
Your strpos() function counts characters, not words.
What you want:
http://php.net/str_word_count
is str_word_count($foo,2), which according to the docs returns an array
with the words and their position in the string. So if you looked at
the key for the 251st element of that array, and subtracted one, that
would be the place to break the string between the 250th and 251st
words. Then you can just use substr($foo, 0, ($keyvalue-1)) to dump
the first part of the text string... Since I'm guessing that
str_word_count() is slow, to avoid running it twice you could use
array_count_values() to count the elements of the returned array. If
it's more than 250, then do the above. If the returned array has less
than 250 elements, you can output the entire string since it's less
than 250 words.
All of this implies that you're happy with what str_word_count defines
as a "word". If you need to be more picky, the function Hans Zaunere
linked to would let you choose exactly what constitutes a word
boundary.
Food for thought: what does your application do if it receives a 10,000
character sequence of A's in a row without spaces? Might it be that
you want to break at 250 words OR a maximum number of characters?
Michael Sims
More information about the talk
mailing list