Dipak
Dipak

Reputation: 57

Count html tags by php in string

Hi there I am requesting you to tell me the simple php script to count special html tag, like <p> in string. I had no idea to try this, since I am the beginner in php.

Upvotes: 2

Views: 7725

Answers (2)

Vikram Jain
Vikram Jain

Reputation: 5588

use a substr_count() function for find a mached substring from string:

  <?PHP
    $text = 'This is a test';
    //Use substr_count for search matched string
    echo substr_count($text, 'is'); // 2

    ?>

Upvotes: 4

You can make use of DOMDocument Class for that .

<?php
$html='<p>Hey hello</p><b>Hey this is bold tag</b><p>Another paragraph</p>';
$dom = new DOMDocument;
$dom->loadHTML($html);
echo $dom->getElementsByTagName('p')->length;// "prints" 2

Upvotes: 6

Related Questions