PHP's json_encode does not escape all JSON control characters

后端 未结 12 1037
旧时难觅i
旧时难觅i 2020-11-28 12:08

Is there any reasons why PHP\'s json_encode function does not escape all JSON control characters in a string?

For example let\'s take a string which spans two rows a

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 12:29

    function escapeJsonString($value) {
        # list from www.json.org: (\b backspace, \f formfeed)    
        $escapers =     array("\\",     "/",   "\"",  "\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).

提交回复
热议问题