jump to navigation

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

Comments»

1. hasin - February 13, 2007

Simple

$wordcount = count(split(” “,$string));

2. ordinarywebguy - February 13, 2007

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. :)

3. Michael J - April 23, 2008

good work, just what i was looking for :), shame Zend haven’t made a built in function for this though.

4. Michael J - April 23, 2008

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 :(