Returning string in a specified number of words using PHP September 22, 2006
Posted by ordinarywebguy in PHP.trackback
function wordTrim($str, $len){
$wordCount = 0;
$charCount = 0;
$length = strlen(strip_tags($str));
for ($i=0; $i<$length; $i++) {
if ($str[$i] == ” “) {
$wordCount++;
$charCount++;
if ($wordCount == $len)
break;
} else {
$charCount++;
} # end if
} # end for loop
$newstr = substr($str, 0, $charCount);
return $newstr;
} # end function$str = “Hello World!”;
print wordTrim($str, 1); // Will print Hello

Simple
$wordcount = count(split(” “,$string));
Hmmmmm! I guess I have inconsistency on the entry title “Getting a number of Words in a string using PHP”. This should then be “Returning string in a specified number of words”. The function given acts like substr() function in php but in terms of words.
Thanks Hasin for your comment! This gives me the attention with the title discrepancy.
good work, just what i was looking for :), shame Zend haven’t made a built in function for this though.
Actually I retract that, your one doesn’t work properly, I made a really good function for it but can’t post since it’s proprietary