【问题标题】:Remove All Unnecessary Whitespaces from JSON String (in PHP)从 JSON 字符串中删除所有不必要的空格(在 PHP 中)
【发布时间】:2014-07-14 14:42:24
【问题描述】:

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

我假设我需要将 preg_replace 与一些巧妙的正则表达式一起使用,以免触及值中的空格。

一个简单的例子是:

之前: '{ "key": "value with whitespaces to maintain" }'

之后: '{"key":"value with whitespaces to maintain"}'

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

【问题讨论】:

  • 一种方法是解析JSON,然后使用自己的编码实现,不是很困难。

标签: php regex json preg-replace minify


【解决方案1】:

一个PHPpreg_解决方案:

preg_replace(
    '/\s(?=([^"]*"[^"]*")*[^"]*$)/', ''
    , '{ "key": "value a with whitespaces to maintain" }'
);

灵感来自:Regex to match all instances not inside quotes

【讨论】:

  • 非常好。我用它来清理 qraphql 查询,然后再将它们发送到 API
【解决方案2】:

PHP =>

语法: ltrim(string,charlist)

例子:

`$str = '{ "name" : " Test Subject" }';`
`$obj = json_decode($str);`
`$obj->name = ltrim($obj->name);`
`var_dump($obj);`

JS/jQuery =>

语法: jQuery.trim( str )

例子:

`var obj={ "name" : " Test Subject" };`
`console.log(obj);`
`obj["name"]=obj.name.trim(); // OR // obj.name.replace(/^\s+/,"");`
`console.log(obj);`

【讨论】:

    【解决方案3】:

    对不起,说的很明显:

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

    它实际上与您的示例完美匹配,请参阅$after

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      相关资源
      最近更新 更多