What are some common pitfalls when using regular expressions to extract tags in PHP?

One common pitfall when using regular expressions to extract tags in PHP is not accounting for nested tags, which can result in incorrect or incomplete extraction. To solve this, you can use a recursive approach to match nested tags properly.

function extractTags($html) {
    preg_match_all('/<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>/si', $html, $matches);
    return $matches[0];
}

$html = '<div><p>Example <strong>text</strong></p></div>';
$tags = extractTags($html);

foreach ($tags as $tag) {
    echo $tag . "\n";
}