Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Replace - Add Slash Before Single Quote [closed]

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!

like image 632
Brian Schroeter Avatar asked Feb 06 '13 23:02

Brian Schroeter


People also ask

How do you replace a single quote in a string?

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.

How do you escape a single quote from a string?

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(\).

How to use backslash in PHP string?

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 ( \\ ).


1 Answers

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.

like image 72
SeanWM Avatar answered Oct 31 '22 17:10

SeanWM