从JSON字符串中删除所有不必要的空格(在PHP中) [英] Remove All Unnecessary Whitespaces from JSON String (in PHP)

查看:1202
本文介绍了从JSON字符串中删除所有不必要的空格(在PHP中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从JSON字符串中删除所有不必要空格(在PHP中)?

How do I remove ALL unnecessary whitespaces from a JSON String (in PHP)?

我假设我需要将preg_replace与一些聪明的正则表达式一起使用,以免触及值中的空白.

I assume that I need to use preg_replace with some clever regex in order to NOT touch the whitespaces that are part of the values.

一个简单的例子是:

之前:'{键":带有要保留的空格的值"}'

Before: '{ "key": "value with whitespaces to maintain" }'

之后:'{键":带有空格的值要维护"}'

After: '{"key":"value with whitespaces to maintain"}'

基本上,我正在寻找一种在不更改任何数据的情况下尽可能缩小和压缩字符串的方法.

Basically, I'm looking for a way to minify and pack the string as tight as possible without changing any data.

推荐答案

很抱歉,显而易见:

$before = '{ "key": "value with whitespaces to maintain" }';
$after  = json_encode(json_decode($before));

它实际上与您的示例完全匹配,请参见$after:

And it actually matches perfectly your example, see $after:

{"key":"value with whitespaces to maintain"}

这篇关于从JSON字符串中删除所有不必要的空格(在PHP中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆