PageRenderTime 1343ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/app/libs/json.minify.php

https://bitbucket.org/chuyskywalker/alkemy
PHP | 59 lines | 49 code | 3 blank | 7 comment | 27 complexity | 1bb8c0fc650931daa0f46e2d3eaa35c5 MD5 | raw file
  1. <?php
  2. /*! JSON.minify()
  3. v0.1 (c) Kyle Simpson
  4. MIT License
  5. https://raw.github.com/getify/JSON.minify/master/minify.json.php
  6. */
  7. function json_minify($json) {
  8. $tokenizer = "/\"|(\/\*)|(\*\/)|(\/\/)|\n|\r/";
  9. $in_string = false;
  10. $in_multiline_comment = false;
  11. $in_singleline_comment = false;
  12. $new_str = array();
  13. $from = 0;
  14. $lastIndex = 0;
  15. while (preg_match($tokenizer,$json,$tmp,PREG_OFFSET_CAPTURE,$lastIndex)) {
  16. $tmp = $tmp[0];
  17. $lastIndex = $tmp[1] + strlen($tmp[0]);
  18. $lc = substr($json,0,$lastIndex - strlen($tmp[0]));
  19. $rc = substr($json,$lastIndex);
  20. if (!$in_multiline_comment && !$in_singleline_comment) {
  21. $tmp2 = substr($lc,$from);
  22. if (!$in_string) {
  23. $tmp2 = preg_replace("/(\n|\r|\s)*/","",$tmp2);
  24. }
  25. $new_str[] = $tmp2;
  26. }
  27. $from = $lastIndex;
  28. if ($tmp[0] == "\"" && !$in_multiline_comment && !$in_singleline_comment) {
  29. preg_match("/(\\\\)*$/",$lc,$tmp2);
  30. if (!$in_string || !$tmp2 || (strlen($tmp2[0]) % 2) == 0) { // start of string with ", or unescaped " character found to end string
  31. $in_string = !$in_string;
  32. }
  33. $from--; // include " character in next catch
  34. $rc = substr($json,$from);
  35. }
  36. else if ($tmp[0] == "/*" && !$in_string && !$in_multiline_comment && !$in_singleline_comment) {
  37. $in_multiline_comment = true;
  38. }
  39. else if ($tmp[0] == "*/" && !$in_string && $in_multiline_comment && !$in_singleline_comment) {
  40. $in_multiline_comment = false;
  41. }
  42. else if ($tmp[0] == "//" && !$in_string && !$in_multiline_comment && !$in_singleline_comment) {
  43. $in_singleline_comment = true;
  44. }
  45. else if (($tmp[0] == "\n" || $tmp[0] == "\r") && !$in_string && !$in_multiline_comment && $in_singleline_comment) {
  46. $in_singleline_comment = false;
  47. }
  48. else if (!$in_multiline_comment && !$in_singleline_comment && !(preg_match("/\n|\r|\s/",$tmp[0]))) {
  49. $new_str[] = $tmp[0];
  50. }
  51. }
  52. $new_str[] = $rc;
  53. return implode("",$new_str);
  54. }