phpjsonreplaceminify

Manually minify a JSON file with PHP string replacements


I have tried to minify a json file with str_replace(), but that doesn't work well as I used it.

//I want to minify a json file with php. 
//Here I am trying to replace ", {" with ",{"

//$result = preg_replace('/abc/', 'def', $string);   # Replace all 'abc' with 'def'

$new = preg_replace('/, {/', ',{', $new); //doesn't work.. why?

Solution

  • As for the specific issue, { is a special character in regular expressions and you need to escape it. See the Meta-characters section of PCRE syntax in the PHP manual. So change the first argument to '/, \{/'. Never mind, as @Hugo demonstrated, it should work, and without telling us how your approach failed, we can't help more.

    More importantly, this is terribly error-prone. What about a JSON string like ['hello, {name}']. Your attempt will incorrectly "minify" the part inside the quotes and turn it into ['hello,{name}']. Not a critical bug in this case, but might be more severe in other cases. Handling string literals properly is a pain, the simplest solution to actually minify JSON strings is to do json_encode(json_decode($json)), since PHP by default does not pretty print or put unnecessary whitespace into JSON.

    And finally, maybe you don't really need to do this. If you are doing this to save HTTP traffic or something, just make sure your server gzips responses, caches properly, etc.