正则表达式替换破坏字符串的字符

In PHP, I'm hoping one can do this with preg_replace and a regex replace all ' with \' and all " with \" and all / with \/.

So replace all characters that can break a string with their escape character counterparts.

Yes you can do that with preg_replace, but in your case I might suggest simply using str_replace() or addslashes().

This

$string = str_replace(Array('"', "'"), Array('\"', "\'"), $string);

or this

$string = addslashes($string);

should do he trick.

I recommend the second. The first should work well to.

preg_replace might cause the code to run a lot slower then the other options.

str_replace and addslashes are good ways to do that. With a preg_replace, don't forget the triple backslash:

$string = <<<'LOD'
I 'love' "marmots" \
LOD;

echo $string.'<br>'.preg_replace('~["\'\\\]~', '\\\$0', $string);