What are some best practices for replacing words in HTML text using PHP without affecting HTML tags?
When replacing words in HTML text using PHP, it's important to ensure that the replacement does not affect any HTML tags present in the text. One way to achieve this is by using the PHP function `preg_replace_callback()` along with regular expressions to only target the text content within HTML tags.
<?php
$html = '<p>This is a <strong>sample</strong> text with <em>HTML</em> tags.</p>';
$word_to_replace = 'sample';
$replacement_word = 'example';
$new_html = preg_replace_callback('/(?<=>)([^<]*)(?=<)/', function($matches) use ($word_to_replace, $replacement_word) {
return str_replace($word_to_replace, $replacement_word, $matches[0]);
}, $html);
echo $new_html;
?>