Jump to content

Counting words in an array


utahfriend

Recommended Posts

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!

 

<?
$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);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/120786-counting-words-in-an-array/
Share on other sites

Using the following code will display all the words in the h1 tags

 

    echo"<h1>Content properties</h1>"; 
    // get h1 tags 
    if($h1[1] != 0){ 
        echo "<br/>H1 Tags found: $h1[1]<ul>"; 
        foreach($h1[0] as $key => $val){ 
            echo "<li>" . htmlentities($val) . "</li>"; 
        } 
        echo "</ul>"; 
    }else{ 
        echo "<br/><div class=\"error\">No H1 Tags found</div><br/>"; 
    } 

 

When I did the print_r I got this result: Array ( [0] => Array ( ) [1] => 0 )

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.