Home  >  Article  >  Backend Development  >  Function to parse special characters in PHP escaped Json

Function to parse special characters in PHP escaped Json

怪我咯
怪我咯Original
2017-04-05 09:47:202160browse

在给一个 App 做 API,从服务器端的 MySQL 取出数据,然后生成 JSON。数据中有个字段叫 content,里面保存了文章内容,含有大量 HTML 标签,这个字段在转 json 的时候需要转义,因为有大量的特殊字符会破坏 json 的结构。

比如这么一段 content:

'Lorem ipsum "dolor" sit amet, consectetur \ adipiscing elit.'

则必须要转化为:

Lorem ipsum \"dolor\" sit amet,\nconsectetur \\ adipiscing elit.

那么有哪些字符是需要转义的呢?看下图:

Function to parse special characters in PHP escaped Json

如果 PHP 版本 > 5.2,json_encode 自带转义。如果是旧版本的 PHP 则可以用下面的函数

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


The above is the detailed content of Function to parse special characters in PHP escaped Json. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn