How can PHP beginners effectively use preg_replace to replace only specific matches in HTML files?

When working with HTML files in PHP, beginners can effectively use preg_replace to replace only specific matches by using regular expressions to target the specific content they want to replace. By crafting a regex pattern that matches only the desired content, beginners can ensure that only those specific matches are replaced while leaving the rest of the HTML file unchanged.

<?php
$html = file_get_contents('example.html');

// Define the regex pattern to match specific content
$pattern = '/<span class="highlight">(.*?)<\/span>/';

// Define the replacement string
$replacement = '<strong>$1</strong>';

// Use preg_replace to replace only specific matches
$html = preg_replace($pattern, $replacement, $html);

// Output the modified HTML
echo $html;
?>