How can negative assertions be used to solve the issue with preg_replace in this context?

The issue with preg_replace in this context is that it is not handling negative assertions correctly, causing unexpected results when trying to replace certain patterns. To solve this, we can use negative assertions to specify what should not be matched in the regular expression pattern, allowing for more precise replacements.

$text = "This is a test string with some unwanted text";
$pattern = '/\b(?!unwanted)\w+\b/';
$replacement = '***';
$result = preg_replace($pattern, $replacement, $text);

echo $result; // Output: "This *** a test string with some unwanted ***"