tags:

views:

75

answers:

4

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

+1  A: 

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

AntonioCS
+1  A: 

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

matpol
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) andthe content - (some something everything).How can i get the name and the content with DomDocument class?
turbod
$meta = $dom->getElementsByTagName('meta');for ($i = 0; $i < $meta->length; $i++) { echo $meta->item($i)->getAttribute('name')." - ".$meta->item($i)->getAttribute('content')."<br />";}
turbod
+1  A: 

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. =)

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