How to count HTML tags

i want to count HTML tags in content coming from database, because im using fckeditor for admin to enter content and it adding p tag for every new paragraph is there any way i can count HTML tags in my content

You can use preg_match for this (
This function returns the number of matches, so all you need is provide the pattern.

If you really want to count tags (both openning and closing) that you can count occurances of e.g. “<”, but you probably want to count the number of openning and closing tags separetly. (look for e.g. “<[^/>]+>” for openning and “</[^>]+>” for closing)

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject . preg_match() returns FALSE if an error occurred.

So better go for preg_match_all()

Oops, haven’t used preg_match() for a while and I forgot about this.

Here is a far more elegant, predictable and programmatic approach.

 * @desc    Returns the total number of XML/HTML
 *          elements contained within a string.
 * @param   String  $sXML
 * @return  Integer
function countElements($sXML)
    $oDomDocument = @DOMDocument::loadHTML($sXML);
    $oNodeList = $oDomDocument->getElementsByTagName('*');
    return (Integer)$oNodeList->length;

$sData = '
    <title>Sample Document/title>
    <h3>This is my list of things to do.</h3>
        <li>Make Breakfast</li>
        <li>Brew Coffee</li>
        <li>Walk Dog</li>
        <li>Wash Dishes</li>

#There are 10 elements contained within the supplied document.
echo sprintf('There are &#37;s elements contained within the supplied document.', countElements($sData));



really thanks silver its working fine this one is good way to count tags for this we need php 5 or it will work on 4 also

I believe you would need to re-code slightly for PHP4 to utilise DOMXML rather than DOMDocument.