How can regular expressions be optimized for better performance when extracting content between specific HTML tags in PHP?

When extracting content between specific HTML tags using regular expressions in PHP, it is important to optimize the regex pattern for better performance. One way to do this is by using non-greedy quantifiers (such as *? or +?) to match as few characters as possible. This prevents the regex engine from backtracking excessively. Additionally, using specific tag names or attributes in the pattern can help narrow down the search and improve efficiency.

$html = '<div>This is some <span>example</span> content</div>';
$pattern = '/<span>(.*?)<\/span>/s'; // Using non-greedy quantifier
preg_match($pattern, $html, $matches);
echo $matches[1]; // Output: example