Reputation: 1575
I want to escape all double quotes which are NOT escaped already.
I am using real_escape_string() already, but I wish to understand what is wrong with the follow regular expression/approach:
$str = '"Hello "" """ world!\"';
preg_replace('/(^|[^\\\\]{1})\"/', '${1}\"', $str);
(PS: I know - \\" will NOT be escaped and MIGHT be a problem in some other cases though this doesn't matter to my script.)
The result was:
\"Hello \"" \""\" world!\"
But I wanted it to be:
\"Hello \"\" \"\"\" world!\"
Upvotes: 3
Views: 109
Reputation: 75222
I think you're on the right track, but you're missing two key elements. The first is that you have to include the quote in the negated character class along with the backslash: [^"\\]*
. When that part runs out of things to match, the next character (if there is one) must be a quote or a backslash.
If it's a backslash, \\.
consumes it and the next character, whatever it is. It might be a quote, a backslash, or anything else; you don't care because you know it's been escaped. Then you go back to gobbling up non-special characters with [^"\\]*
.
The other missing element is \G
. It anchors the first match to the beginning of the string, just like \A
. Each match after that has to start where the previous match ended. This way, when the final "
in the regex comes into play, you know that every character before it has been examined, and you are indeed matching an unescaped quote.
$str = '"Hello "" """ world!\"';
$str = preg_replace('/\G([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"/', '$1\"', $str);
Upvotes: 2
Reputation: 43810
Here is how you escape your sql:
$str = mysql_real_escape_string($str);
or:
$str = mysqli_real_escape_string($str);
or
$str = *_real_escape_string($str);
// * is your db extention
Or you can use PDO to parametrize your input.
Upvotes: 3