How can capturing groups be used in PHP regex patterns to modify and replace parts of a string?

Capturing groups in PHP regex patterns allow us to isolate specific parts of a matched string and modify or replace them as needed. By enclosing the desired parts of the pattern in parentheses, we can refer to them later using backreferences. This is useful for tasks such as rearranging parts of a string, extracting specific information, or applying different replacements based on captured groups.

$string = "Hello, my name is John Doe.";
$pattern = '/Hello, my name is (\w+) (\w+)\./';
$replacement = 'Nice to meet you, $2 $1!';
$result = preg_replace($pattern, $replacement, $string);

echo $result; // Output: Nice to meet you, Doe John!