Here's how to get all instances of one tag, or all top-level tags, from a string of HTML. Getting all nested tags can be tricky, but if you know you want everything one level in from the body tag, for example, this is an easy method.
function get_tags($html, $tag = '')
{
if ($tag) {
preg_match_all("/<(". $tag .")([^>]*)>(.*)<\/". $tag .">/is", $html, $matches1, PREG_SET_ORDER);
preg_match_all("/<(". $tag .")([^>]*)\/(\s*)>/is", $html, $matches2, PREG_SET_ORDER);
}
else {
preg_match_all("/<([\w]+)([^>]*)>(.*)<\/\1>/is", $html, $matches1, PREG_SET_ORDER);
preg_match_all("/<([\w]+)([^>]*)\/(\s*)>/is", $html, $matches2, PREG_SET_ORDER);
}
return array_merge($matches1, $matches2);
}