What is the purpose of using back references in preg_replace in PHP?

When using preg_replace in PHP, back references allow you to reference captured groups from the regular expression pattern within the replacement string. This can be useful for dynamically inserting matched content into the replacement string. By using back references, you can create more flexible and dynamic replacements in your regex operations.

$string = "Hello, my name is John Doe.";
$pattern = "/(John) (Doe)/";
$replacement = "$2, $1";
$new_string = preg_replace($pattern, $replacement, $string);

echo $new_string; // Output: Hello, my name is Doe, John