turbod
turbod

Reputation: 1988

How to count html tags and contents

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

Upvotes: 0

Views: 2560

Answers (4)

ghostdog74
ghostdog74

Reputation: 342363

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

Upvotes: 1

Jens
Jens

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

AntonioCS
AntonioCS

Reputation: 8496

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

Upvotes: 1

matpol
matpol

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

Related Questions