Oops, I forget to consider, what would happened with HTML tags. Thank you Justin. Finally I did a function similar to yours, but the addition of the TAG control is almost perfect solution. (To trunk a word of two or three words, does not worth. No need such complicated script (with dictionary) for that)
Cheers! -----Original Message----- From: Justin French [mailto:[EMAIL PROTECTED] Sent: jueves, 05 de febrero de 2004 0:59 To: Brian Paulson Cc: [EMAIL PROTECTED]; [EMAIL PROTECTED] Subject: Re: [PHP] Extract of a Paragraph On Thursday, February 5, 2004, at 02:35 AM, Brian Paulson wrote: > $string = substr($stringname,0,50); > > echo $string; > > http://www.php.net/substr No, that's 50 *characters* -- he wanted 50 *words*. A quick and reasonably accurate[1] solution would be this: Daniel, There's a few things you need to look out for. If there's tags (like <b> or <a>) in the text, and you chop the text inside an open tag, it will break your pages, cause them to be invalid, and make them look really strange. So the first thing you want to do with the text is strip the tags. I'd say the next issue is to only append the 'read more' link if the article is great than the teaser limit -- that way 'read more' only appears when it's correct. You should wrap it in a function so that you only ever write this code once too. Here's a stripped-down version of what I use: <? function chopper($input,$wordcount,$append='') { $input = trim(strip_tags($input)); $words = explode(' ',$input); $output = ''; for($i=0; $i<=$wordcount; $i++) { $output .= $words[$i].' '; } trim($output); if( ($i == $wordcount) && (!empty($append)) ) { $output .= $append; } return $output; } echo chopper($myText,50,"... <a href='foo'>read more</a>"); ?> [1]: It's reasonably accurate in that it breaks words on spaces, then glues them back together up to the limit. However, there are some words which you may consider to have a space in them, but still be considered one word. A perfect example would be "Leonardo da Vinci" which the above function will see as 3 words, and you may consider it to be 2. Justin French -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php