The answer to a slightly different question
This is what is called a "XY problem". You are trying to solve problem Y ("Removing SQL-problematic characters from JSON") when your actual problem is problem X:
I need to fetch it later from DB and hold it in a javascript variable. Then I call a fromJson method of the jQuery plugin I am using.
So what you need is: "a way of storing a textual value in a SQL-neutral, JSON-neutral, Javascript-neutral representation".
You can do this by using Base64. Use Base64 as the "common language" between your app layers - SQL, Javascript and PHP. Then decode values when they enter a boundary, and encode them when they go out again:
$value = "string with weird JSON that won't go into SQL";
$val2 = base64_encode($value);
...now $val2 is stored into SQL and can be retrieved with no problems
(search can be difficult but can be done, somewhat).
Then you retrieve the $val2
and can store it into Javascript with no problems, only remember it's base64. Yes, it'll take somewhat more space, but nowadays is that really a problem?
// Value recovered from SQL through PHP
var base64val = '{$val2}';
// base64val is a safe string, but useless.
var trueval = btoa(base64val);
// trueval is a JSON string, but not yet decoded.
var fromjson = JSON.parse(trueval);
// finally fromjson holds the real value
Now, you have a workflow into which anything goes - you can put slashes, dollar signs, quotes, double quotes and, more importantly, a lot of UTF8 characters that would have wrecked my previous answer (you may want to seek some thrills reading about "malformed UTF8 attacks and where to find them").