Are there any best practices for excluding certain HTML tags from str_ireplace replacements in PHP?

When using str_ireplace in PHP to replace certain HTML tags, it's important to exclude specific tags from being replaced to avoid unintended consequences. One way to achieve this is by using regular expressions to match and exclude the tags from the replacement process. By defining a pattern that captures the tags to be excluded, we can ensure that only the desired tags are replaced while leaving the excluded tags untouched.

// Define the input string containing HTML tags
$input = '<p>This is a <b>sample</b> text with <i>HTML</i> tags.</p>';

// Define the tags to be excluded from replacement
$excluded_tags = array('<b>', '</b>');

// Define the replacement text
$replacement = 'replacement';

// Exclude specific HTML tags from replacement using regular expressions
$output = preg_replace_callback('/(<\/?[^>]*>)/', function ($match) use ($excluded_tags, $replacement) {
    if (in_array($match[1], $excluded_tags)) {
        return $match[1];
    } else {
        return $replacement;
    }
}, $input);

// Output the modified string
echo $output;