How should I go about adding slashes to only single quotes and ignoring double quotes?
I am using php. I would only like to escape single quotes to prevent my php mysql queries from breaking.
I am thinking a regular expression search and replace will be the most helpful.
preg_replace_all("/([^\])'/","$1\'",$yourStrHere) will do what you’re asking:
- “/([^\])’/” yields the regex /([^\])’/, which says “match on any single character that’s not a backslash followed by a single quote, and capture the character before the quote.”
- “$1\'” says “replace with the captured character followed by a backslash and a single quote”
Bill’s answer about parametrized queries using the mysqli or PDO APIs is really, really good advice. It’s easier and more effective to let your database API handle this than to do it yourself — the people who wrote these APIs (and the people who worked on the native backends for those APIs) have probably put more time and effort into addressing security and performance issues than most of us can hope to spend ourselves.
Okay am really late to this post but adding this answer hoping that it might help someone landing at this question. While @Weston C has given a regex solution, there is a php function for doing this- addcslashes (http://php.net/manual/en/function.addcslashes.php):
string addcslashes ( string $str , string $charlist ) Returns a string with backslashes before characters that are listed in charlist parameter.
str_replace("'", "\\'", $string) should work. But as Gumbo stated above, you should use the library functions if you’re trying to escape MySQL queries.
mysql_real_escape_string. It escapes just the required characters while regarding the character encoding of your MySQL connection.
If you use query parameters for dynamic values, you don’t need to do any escaping at all.