Skip to content
PHP Logo

Are there any alternative methods to achieve the desired text replacement without affecting HTML elements?

When replacing text in a webpage using PHP, it's important to ensure that HTML elements are not inadvertently affected. One alternative method to achieve text replacement without affecting HTML elements is to use regular expressions with the `preg_replace` function. By targeting specific text patterns and avoiding HTML tags, you can safely replace text without impacting the underlying HTML structure.

php
<?php

// Original text with HTML elements
$html = '<p>Hello, <strong>world</strong>!</p>';

// Text to replace
$old_text = 'world';
$new_text = 'universe';

// Use regular expressions to replace text without affecting HTML elements
$new_html = preg_replace('/\b' . preg_quote($old_text, '/') . '\b/', $new_text, $html);

echo $new_html;

?>