How can backreferences be used in a replacement function in PHP?

Backreferences can be used in a replacement function in PHP by referencing captured groups in the regular expression pattern. To use backreferences, you need to enclose the captured group in parentheses and refer to it using \1, \2, etc. in the replacement string. This allows you to dynamically insert the matched text from the captured group into the replacement string.

// Example of using backreferences in a replacement function in PHP
$string = "Hello, World!";
$pattern = '/(Hello), (World)/';
$replacement = '$2, $1'; // Reverses the order of the words
$new_string = preg_replace($pattern, $replacement, $string);

echo $new_string; // Outputs: "World, Hello"