PHP’s json_encode does not escape all JSON control characters

function escapeJsonString($value) {
    # list from www.json.org: (\b backspace, \f formfeed)    
    $escapers =     array("\\",     "https://stackoverflow.com/",   "\"",  "\n",  "\r",  "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t",  "\\f",  "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
  }

I’m using the above function which escapes a backslash (must be first in the arrays) and should deal with formfeeds and backspaces (I don’t think \f and \b are supported in PHP).

Leave a Comment