Page 1 of 1

Counting words in an array

Posted: Thu Aug 21, 2008 6:37 pm
by utahfriend
I have some code that I cannot make work. It uses PHP to find the words in the <h1> tags in html and then counts the words. However, whenever I run it, no matter how many words are in the <h1> tags, it always returns a "1". I need help to find what is wrong with my code! Any help is appreciated!

Code: Select all

<?
$file="http://www.globalmarketingplus.com";
$h1 = get_h1($file); 
$h1_words=count_words($h1);
 
echo "There are ".$h1_words." in h1 tags";
 
function get_h1($file){ 
    $h1tags = preg_match_all("/(<h1.*>)(\w.*)(<\/h1>)/isxmU",$file,$patterns); 
    $res = array(); 
    array_push($res,$patterns[2]); 
    array_push($res,count($patterns[2])); 
    return $res; 
} 
 
function count_words($str) {
    $no = explode(" ",$str);
    $no = strip_tags($no);
    return count($no);
}
?>

Re: Counting words in an array

Posted: Thu Aug 21, 2008 8:25 pm
by lukewilkins
Your explode is turning the array into a string ... count() is not for that. Why are you stripping the tags at this step? That should not effect the array count.

Just do this:

Code: Select all

function count_words($str) {
    return count($str);
}
or if you really need those tags stripped:

Code: Select all

function count_words($str) {
    foreach($str as $value){
        $cnt[] = strip_tags($value);
    }
    return count($cnt);
}
Hope that helps.
Luke

Re: Counting words in an array

Posted: Thu Aug 21, 2008 8:53 pm
by utahfriend
I was stripping out the tags to get rid of any html code in the H1 tag. The H1tag in the file we are looking at is as follows: "Web Design & Hosting<br>Locally & Nation Wide". I was hoping to remove the <br>. The count should return the number of words in the tag, but it was returning 1. Now that I tried your suggestion, it returns 2. Why does it not return the correct number? I would like to also like to be able to list the words that it finds in the tag. When I add the following code, I only get the word "array" instead of a list of words.

Code: Select all

    foreach($no as $c) {
        echo "h1: $c<br>";
    }
 

Re: Counting words in an array

Posted: Sat Aug 23, 2008 7:22 am
by lukewilkins
As I said, count() *does not* work with strings ... only arrays and object properties. http://us3.php.net/count

If the count() function returns 1 it means that the var you gave it is invalid to be counted (hence, not an array or object property). It will only return 0 if the var is NULL.

Sorry, do a print_r($yourarray); and post that here so I can see. And sorry, explode breaks it to an array ... not string. I'll take a look at this some more.