0

Why does the following work for removing a \ before a single quote but not a double quote?

UPDATE: the code below works but not when the single ' or " iss in the first position. Is there a way to fix that?

Input is coming from a form where I have no control of what people type in.

 $x[0] = $_POST['line1'];
   $x[1] = $_POST['line2'];
   $x[2] = $_POST['place'];



   //check for apostrophes and quotes
   for($i=0;$i<3;$i++){
      while( strpos($x[$i], "\'") != false){
          $pos = strpos($x[$i], "\'");
          $x[$i] = substr_replace($x[$i],"",$pos,1);
      }
      while( strpos($x[$i], '\"') != false){
          $pos = strpos($x[$i], '\"');
          $x[$i] = substr_replace($x[$i],"",$pos,1);
      }
DCR
  • 14,737
  • 12
  • 52
  • 115
  • You could also replace your inner loops by just saying replace them with just the quotes... `$x[$i] = str_replace(["\\\"","\'"], ['"', "'"], $x[$i]);` – Nigel Ren Oct 31 '19 at 15:30
  • Just checked and `for($i=0;$i<3;$i++){ $x[$i] = str_replace(["\\\"","\'"], ['"', "'"], $x[$i]);}` seems to work – Nigel Ren Oct 31 '19 at 16:02
  • sorry about that. I tried again and it works like a charm. also your marked as duplicate is right on. I changed != to !== and that also works. Thanks – DCR Oct 31 '19 at 16:09

1 Answers1

0

Taken from the PHP manual -

Single quoted ¶ 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 (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

That should answer your question.

aynber
  • 22,380
  • 8
  • 50
  • 63
Xerith
  • 312
  • 1
  • 9