Escaping single quote

$var2=str_replace("\'", "", $var1)

Can I say the code above is escaping single quote?
or
Can I say the code below is escaping single quote?

$var2=str_replace("'", "\'", $var1)

Depends on what you’re doing :wink:

Your first example will never escape anything, the second might, depending on the context.

Consider this HTML:

alt='Conan O'Brian'

Any browser parsing will set start a the single quote and read up the first single quote after that. So the alt will be parsed as Conan O and regard the rest as a syntax error.

To fix it you can do one of two things:

  1. Use double quotes for the alt attribute: ``alt=“Conan O’Brian”`. Now the browser will parse from double quote to double quote. The single quote has no special meaning anymore.

  2. Escape the single quote in the name: alt='Conan O\'Brian'. With that you’re basically saying to the browser “look, I know the next character is a single quote, and it would indicate the end of the string, but I don’t want that, just treat it as a single quote”

Question to the reader: what happens when I combine these two solutions, so switching from single quotes and escaping the single quote?

Well the first one is destroying the quote, so rpkamp’s right, you’ll never escape anything with it :stuck_out_tongue:

The second one will put ’ into your string. What happens to it after that, as Ramon says, varies.

But be careful - "\"" will NOT put the \ into your string (because it gets consumed by the parser).