Home » Php » php – How should I go about adding slashes to only single quotes and ignoring double quotes?

php – How should I go about adding slashes to only single quotes and ignoring double quotes?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

Thank you!

Edit:
I am thinking a regular expression search and replace will be the most helpful.

How to&Answers:

Well, 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”

BUT…

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.

Answer:

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.

Answer:

A simple str_replace("'", "\\'", $string) should work. But as Gumbo stated above, you should use the library functions if you’re trying to escape MySQL queries.

Answer:

Use mysql_real_escape_string. It escapes just the required characters while regarding the character encoding of your MySQL connection.

Answer:

If you use query parameters for dynamic values, you don’t need to do any escaping at all.

You can use query parameters in the mysqli extension or the PDO extension (I prefer PDO). The old mysql extension doesn’t support query parameters.