Function to parse special characters in PHP escaped Json

怪我咯
Release: 2023-03-07 10:30:01
Original
2081 people have browsed it

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

比如这么一段 content:

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

则必须要转化为:

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

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

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; }
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!