Home>Article>Backend Development> How to prevent json_encode from automatically escaping slash "/" in PHP?

How to prevent json_encode from automatically escaping slash "/" in PHP?

青灯夜游
青灯夜游 Original
2020-04-25 15:07:43 3915browse

php中怎么让json_encode不自动转义斜杠“/”?下面本篇文章给大家介绍一下PHP中让json_encode不自动转义斜杠“/”的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

How to prevent json_encode from automatically escaping slash

最近将使用爬虫爬取的链接保存到 mysql 数据库中时,发现我将链接使用 json_encode 保存时候,在数据库中却显示了转义字符,我并不需要这转义的,看起来不清晰而且占用存储空间。

后来发现在默认的情况之下使用 json_encode 对数组进行 json 格式的转换时候会自动的将数据中含有斜杠的字符串进行转义,但是我们往往有的时候不需要药对它们进行转义的,本文说说如何使用 json_encode 不自动转义斜杠。

对于如下数组 $a,现有两种办法解决:

$a = array( 'http://www.baidu.com', 'http://www.baidu.com', 'http://www.baidu.com', 'http://www.baidu.com', 'http://www.baidu.com' );

其一,正则替换:

$a = str_replace("\\/", "/", json_encode($a)); var_dump($a);

其二,若 php 版本是 5.4 及以上的话:

var_dump(json_encode($a,JSON_UNESCAPED_SLASHES));

更多相关知识,请关注PHP中文网!!

The above is the detailed content of How to prevent json_encode from automatically escaping slash "/" in PHP?. 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