0

I have a problem with regular expressions! How can i count html tags with regex?

3
  • You're joking, aren't you? If not, no, you can't and you shouldn't. Read stackoverflow.com/questions/1732348/…
    – Amarghosh
    Mar 17, 2010 at 9:32
  • 3
    Just count the number of < - this will give you the same kind of precision you can get with a regex. Mar 17, 2010 at 9:35
  • Also, even if you're prepared to deal with the problems of using it, regex doesn't do counting. At the very least you have to use, e.g., perl to load the html into a variable and do a split() on "<" (excluding "<!--"), then check the length of the resulting array.
    – Timo
    Mar 17, 2010 at 9:47

4 Answers 4

2

Don't use regexp use the DOM. I am not sure how you would do it but it will almost certainly be easier with the DOM: http://php.net/manual/en/book.dom.php

2
  • Thanks. DomDocument class is good, and solve my problem, but i have one last question. i have meta tags: <meta name="keywords" content="some something everything"/> i need the name - (keywords) and the content - (some something everything). How can i get the name and the content with DomDocument class?
    – turbod
    Mar 17, 2010 at 11:14
  • $meta = $dom->getElementsByTagName('meta'); for ($i = 0; $i < $meta->length; $i++) { echo $meta->item($i)->getAttribute('name')." - ".$meta->item($i)->getAttribute('content')."<br />"; }
    – turbod
    Mar 17, 2010 at 11:27
1

You don't! Why don't you try the DOMDocument class

1

Regular expressions are not designed to do that. There sure is a better solution to your problem, just check the other answers.

If you just need this once, as a quick and dirty hack, and do not care about edge cases (like escaped tags used in strings), you could use "<\w+" to match the starting tags, and count the number of matches.

But you should not do it this way. =)

1
$data=file_get_contents("file");
$data=preg_replace("/\n+|[[:blank:]]+/","",$data);
print "number of tags: ". substr_count($data, '<');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.