I'm trying to escape a single quote within my PHP by adding a slash before it. Unfortunately, I've been unable to get it working with str_replace and I'm wondering if I'm doing something wrong.
What I have is the following ...
$string = 'I love Bob's Pizza!';
$string = str_replace("'", "\\'", $string);
echo $string;
When I use this, for some reason it's not replacing the single quote with "\'" as it should.
Any help is greatly appreciated!
Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.
You need to escape single quote when the literal is enclosed in single code using the backslash(\) or need to escape double quotes when the literal is enclosed in a double code using a backslash(\).
The simplest way to specify a string is to enclose it in single quotes (the character ' ). To specify a literal single quote, escape it with a backslash ( \ ). To specify a literal backslash, double it ( \\ ).
Why not use addslashes?
$string = "I love Bob's Pizza!";
$string = addslashes($string);
echo $string;
UPDATE: If you insist on your way it's because you're not escaping the single quote. Try:
$string = 'I love Bob\'s Pizza!';
$string = str_replace("'", "\\'", $string);
echo $string;
You simply can't do what you're doing because it causes a syntax error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With