Reputation: 271
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.
Upvotes: 0
Views: 53
Reputation: 89547
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);
Upvotes: 1
Reputation: 14532
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.
Upvotes: 2
Reputation: 71384
Yes you can do that with preg_replace, but in your case I might suggest simply using str_replace()
or addslashes()
.
Upvotes: 0