Well I figure that I want to trim a string after say, 100 or 200 words (want to ensure that feeds I'm bringing in to post for aggregator are just excerpts and not entire posts). So now I'm figuring I may as well go about this by counting space characters " "and after say... 100 space characters I'd like to trim & return this string from the function that'll be trimming (right after 100th occurance of space character of course). So uhh... once again any help on this would be greatly appreciated
Here is one way of doing it: <?php $text = "Pack my box with five dozen liquor jugs"; $maxwords = 6; for ($i=0,$words=0;$i<strlen($text);$i++) { if ($text[$i] == " ") $words++; if ($words == $maxwords) break; $newtext .= $text[$i]; } echo $newtext; ?> PHP: Just set your $text and $maxwords as appropriate, $newtext will contain the truncated string.
BWAHAHAHAHA!!!! I was spending hours figuring out why the "new string" was looping continuously & nothing was trimmed, only to realize that I wasn't matching my current variables to what you had was for the old string & new string THANKS stoli !!!
This is a little more forgiving than counting spaces. $str[0] will contain the string. <?php $text = 'this is a sentence, that has some words -- for testing with -- and stuff, ja know? chicken bo ?'; $words = 9; preg_match('#^[^a-z]*([a-z-]+[^a-z-]+){1,'.$words.'}#', $text, $str); var_dump($str); ?> PHP: