Remove all unnecessary spaces from a JSON string (in PHP)

How to remove ALL unnecessary spaces from a JSON string (in PHP)?

I assume that I need to use preg_replace with some clever regex so as NOT to touch spaces that are part of the values.

A simple example would be:

Before: '{"key": "value with spaces for support"}'

After: '{"key": "value with spaces for support"}'

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

+6
source share
3 answers

Sorry that explicit:

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

And it really matches your example, see $after :

 {"key":"value with whitespaces to maintain"} 
+20
source

PHP preg_ solution:

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

Inspired by: Alternative to regex: matching all instances not inside quotes

+2
source

PHP =>

Syntax: ltrim(string,charlist)

Example:

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

JS / jQuery =>

Syntax: jQuery.trim( str )

Example:

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

Source: https://habr.com/ru/post/969840/


All Articles