老版本PHP转义Json里的特殊字符的函数_php技巧

WBOY
Release: 2016-05-16 20:14:18
Original
921 people have browsed it

在给一个 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.

如果 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

经常会用到,记录一下,希望对你有帮助。

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
Popular Tutorials
More>
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!