How can backreferences be effectively used in preg_replace for more complex string manipulations in PHP?

Backreferences in preg_replace allow you to reference captured groups in the replacement string, enabling more complex string manipulations. To effectively use backreferences, you need to capture the desired parts of the input string using parentheses in the regular expression, and then reference these captured groups using \1, \2, etc. in the replacement string.

$input = "Hello, my name is John Doe.";
$output = preg_replace('/Hello, my name is (\w+) (\w+)\./', 'Nice to meet you, $1 $2!', $input);
echo $output;