Skip to content
PHP Logo

How does PHP handle the conversion of $1 from a string to a variable in functions like preg_replace()?

When using functions like preg_replace() in PHP, the dollar sign ($) is a special character that denotes a backreference in the replacement string. To prevent PHP from interpreting $1 as a variable, you can escape the dollar sign with a backslash (\$) in the replacement string.

php
$string = "Hello, World!";
$pattern = "/Hello/";
$replacement = "Goodbye, ";
$result = preg_replace($pattern, $replacement, $string);
echo $result; // Output: Goodbye, World!