NYCPHP Meetup

NYPHP.org

[nycphp-talk] strpos with space

CED Consult at CovenantEDesign.com
Mon Jul 25 16:04:14 EDT 2005


I've always used Split()


----- Original Message ----- 
From: "Michael Sims" <jellicle at gmail.com>
To: "NYPHP Talk" <talk at lists.nyphp.org>
Sent: Monday, July 25, 2005 4:01 PM
Subject: Re: [nycphp-talk] strpos with space


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

 
_______________________________________________
New York PHP Talk Mailing List
AMP Technology
Supporting Apache, MySQL and PHP
http://lists.nyphp.org/mailman/listinfo/talk
http://www.nyphp.org




More information about the talk mailing list