7

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!

Brian Schroeter
  • 1,583
  • 5
  • 22
  • 41

1 Answers1

16

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.

SeanWM
  • 16,789
  • 7
  • 51
  • 83