Tags
Asked 2 years ago
9 Jun 2021
Views 227
ajamil

ajamil posted

Escaping special characters in str_replace PHP function

Escaping special characters in "str_replace" PHP function
kord

kord
answered Apr 25 '23 00:00

In PHP, str_replace() function is used to replace all occurrences of a substring with another substring in a given string. The function takes three parameters: the substring to search for, the substring to replace with, and the string to search and replace within.

However, there are certain special characters that have a special meaning in the replacement string, such as $, \, and {} . To use these characters literally in the replacement string, they must be escaped with a backslash \.

For example, let's say we have a string "Hello, $name!" If we want to replace $name with the value of a variable $username, we can use the following code:



$name = "John";
$string = "Hello, $name!";
$replacement = "world";
$new_string = str_replace("$name", $replacement, $string);
echo $new_string; // Output: "Hello, world!"

However, if we want to replace $name with the string literal $username , we need to escape the $ character in the replacement string:



$name = "John";
$string = "Hello, $name!";
$replacement = "\$username";
$new_string = str_replace("$name", $replacement, $string);
echo $new_string; // Output: "Hello, $username!"

In this example, we have escaped the $ character in the replacement string using a backslash, so it is interpreted literally rather than as a variable reference.
Post Answer