How can one ensure that parentheses around words are preserved when using preg_replace in PHP?
When using preg_replace in PHP to manipulate strings, parentheses are special characters used for capturing groups. To ensure that literal parentheses around words are preserved, you need to escape them with backslashes (\) in the regular expression pattern. This tells PHP to treat them as literal characters rather than special regex symbols.
$string = "This is a (test) string with (parentheses).";
$pattern = "/\\(test\\)/";
$replacement = "(example)";
$new_string = preg_replace($pattern, $replacement, $string);
echo $new_string; // Output: This is a (example) string with (parentheses).