Reputation: 1988
I have a problem with regular expressions! How can i count html tags with regex?
Upvotes: 0
Views: 2560
Reputation: 342363
$data=file_get_contents("file");
$data=preg_replace("/\n+|[[:blank:]]+/","",$data);
print "number of tags: ". substr_count($data, '<');
Upvotes: 1
Reputation: 25563
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. =)
Upvotes: 1
Reputation: 3074
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
Upvotes: 2