String Replace - Add Slash to Single Quote

I am trying to avoid a single quote inside my PHP by adding a slash in front of it. Unfortunately, I was not able to get it to work with str_replace, and I wonder if I am not doing something wrong.

I have the following ...

$string = 'I love Bob Pizza!'; $string = str_replace("'", "\\'", $string); echo $string; 

When I use this, for some reason it does not replace the single quotation mark "\", as it should be.

Any help is much appreciated!

+4
source share
1 answer

Why not use addslashes ?

 $string = "I love Bob Pizza!"; $string = addslashes($string); echo $string; 

UPDATE: If you insist on your path because you are not avoiding a single quote. Try:

 $string = 'I love Bob\ Pizza!'; $string = str_replace("'", "\\'", $string); echo $string; 

You simply cannot do what you are doing, because it causes a syntax error.

+9
source

All Articles