How can grouping patterns in preg_replace help in achieving specific replacements in PHP?

Grouping patterns in preg_replace allows for specific parts of the matched pattern to be captured and referenced in the replacement string. This can be useful when you want to replace certain parts of a string while keeping others intact. By using capturing groups in the regular expression pattern and referencing them in the replacement string, you can achieve more targeted and specific replacements in PHP.

// Example of using grouping patterns in preg_replace to achieve specific replacements
$string = "Hello, [Name]! How are you, [Name]?";
$newString = preg_replace('/\[Name\]/', 'John', $string);

echo $newString; // Output: Hello, John! How are you, John?