Replacing 2 characters with with preg_replace

I'm using preg_replace to replace ' and " with a backslash in front of them so that I don't get problems with my MySQL INSERT queries. But at the moment I can only replace them with one charater as below:

At the moment that just replaces both ' and " with ' which isn't ideal. Can anyone tell me how I'd be able to replace them with the respective charater. (e.g. ' would be replaced with \' and " would be replaced with\")

... I'm not entirely sure why'd you write your own function when the built-in addslashes function works perfectly well.

Aye, I was wondering the same thing.

addslashes() is slightly different - it escapes a couple of extra characters (including '\' and NUL). However, these (especially \) need to be escaped anyway.

So, to fill in the original example...

$unedited = $_POST['content'];
$content = addslashes($unedited);

However, you might be looking to learn how to use preg_replace... so we'll go back to the original example.

You can use preg_replace() like Fungus did with str_replace - sending an array as the search and replacement parameters.

The problem with your example is that you're only presenting one thing for the replacement parameter - "\'".

In order to replace ' with \' and " with \" you need to do one of a few things - perform two preg_replaces (one for each replacement), use arrays within the preg_replace, or use a variable in the regex to print the quote based on what the search found. I'm not that good with regex, so I'm not sure if you can do that... but I think you can.

Anyhow, here's an example of how you could use arrays to perform the desired function with preg_replace.