Reputation: 50355
So, when I save the data into database, PHP will add a \ on single or double quotes. That is good.
However, when data is passed back to the client using json_encode(); TEXT like McDonald's is STORED as McDonald's in the DB but once passed back from PHP to js, it will be encoded as McDonald\'s
Since I'm using jQuery, is there any plugin to easily do that? or any function I should use to strip the slashes correctly? obviously, if there is case like \\\\s
, the function should return \s
. :)
Sorry guys. I think I made my question too complicated. How about I make it simpler..
If I have a javascript variable:
var abc = "McDonald\'s";
var bcd = "I need a slash \\ ";
var cde = "save the double quote \"";
how can I strip the \' ? what the regex I should use?
Upvotes: 1
Views: 22990
Reputation: 220
Try this too
function stripslashes (str) {
return (str + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
}
Upvotes: 1
Reputation: 877
Use: http://au.php.net/manual/en/function.mysql-real-escape-string.php before storing into database.
Use a custom function like this before writing onto any user interface:
function unescape($string)
{
$search = array("\\x00", "\\n", "\\r", "\\\x1a");
$replace = array("\x00","\n", "\r", "\x1a");
$retString = str_replace($search, $replace, $string);
$search = array("\'", '\\'.'"');
$replace = array( "'", '"',);
$retString = str_replace($search, $replace, $retString);
$search = array("\\\\");
$replace = array( "\\");
$retString = str_replace($search, $replace, $retString);
return $retString
}
Upvotes: 0
Reputation: 490233
I would take care of the main problem - magic_quotes
is enabled.
I would disable it and use proper escaping methods with your database.
Then you don't have to worry about PHP magically adding slashes.
If you are talking about slashes when using json_encode()
, it does that for a reason.
Use a JSON parser in JavaScript and you won't see them (unless something else is improperly encoding them).
Upvotes: 4
Reputation: 112827
It's actually highly discouraged to use this "magic quotes" feature that inserts slashes. In general, you never want to store data in the database in an escaped format; you want to do the escaping and encoding in the output.
Upvotes: 8