0

Please help I want to loop between these tags div ..

<p> answer 1 </p>   
<div class='right'>Obama</div>
<p> answer 2 </p>
 <div class='wrong'>Brazil</div>
<p> answer 3 </p>
 <div class='right'>Tennis</div>
<p> answer 4 </p>
 <div class='wrong'>Sand</div>
<p> answer 5 </p>
 <div class='right'>Nike</div>

and count the tag div that has the class 'right'..and echo the sum of these tags, in this exemple the sum is 3.

WEB BELGE
  • 3
  • 1
  • 1
    you'll need to start coding, you can start by using [`DOMDocument`](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) for parsing HTML using PHP – Kevin Jan 26 '16 at 02:30
  • an unorthodox way... `echo substr_count($html, "
    "); // 3`
    – Andrew Jan 26 '16 at 03:38

2 Answers2

3

You can use domdocument for this, or a number of other libraries. Here's a simple example:

$html = "
<p> answer 1 </p>   
<div class='right'>Obama</div>
<p> answer 2 </p>
 <div class='wrong'>Brazil</div>
<p> answer 3 </p>
 <div class='right'>Tennis</div>
<p> answer 4 </p>
 <div class='wrong'>Sand</div>
<p> answer 5 </p>
 <div class='right'>Nike</div>";
$thedoc = new DOMDocument();
$thedoc->loadHTML($html);
$divs = $thedoc->getElementsByTagName('div');
$rights = 0;
foreach($divs as $div){
    if($div->getAttribute('class') == 'right'){
        $rights++;
    }
}
echo $rights;

Output:

3
chris85
  • 23,846
  • 7
  • 34
  • 51
0

You could do this in many ways.

  1. Create a regex to search HTML code
  2. Loop using strpos to find a specific string (Not great if there are spaces)
  3. Use a third party application like simple_html_dom to fetch the elements most accurately (My favorite).

I'll just quickly show you how to do #3.

Finding element count using SimpleHTMLDom

$str = "<p> answer 1 </p>   
<div class='right'>Obama</div>
<p> answer 2 </p>
 <div class='wrong'>Brazil</div>
<p> answer 3 </p>
 <div class='right'>Tennis</div>
<p> answer 4 </p>
 <div class='wrong'>Sand</div>
<p> answer 5 </p>
 <div class='right'>Nike</div>";

$html = str_get_html($str);
echo count($html->find("div[class='right']"));

Download and include the class from here

Community
  • 1
  • 1
Matt
  • 2,851
  • 1
  • 13
  • 27