var-dump-to-array.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * dolphin. Collection of useful PHP skeletons.
  4. * Copyright (C) 2013 Johannes 'Banana' Keßler
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
  8. *
  9. * You should have received a copy of the
  10. * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11. * along with this program. If not, see http://www.sun.com/cddl/cddl.html
  12. */
  13. /**
  14. * can return the output of var_dump() into a variable.
  15. * nested and complex strutures are supported.
  16. * based on an idea from stackoverflow
  17. *
  18. * @param string The output of var_dump()
  19. */
  20. function var_dump_to_variable($str) {
  21. if (strpos($str, "\n") === false) {
  22. //Add new lines:
  23. $regex = array(
  24. '#(\\[.*?\\]=>)#',
  25. '#(string\\(|int\\(|float\\(|array\\(|NULL|object\\(|})#',
  26. );
  27. $str = preg_replace($regex, "\n\\1", $str);
  28. $str = trim($str);
  29. }
  30. $regex = array(
  31. '#^\\040*NULL\\040*$#m',
  32. '#^\\s*array\\((.*?)\\)\\s*{\\s*$#m',
  33. '#^\\s*string\\((.*?)\\)\\s*(.*?)$#m',
  34. '#^\\s*int\\((.*?)\\)\\s*$#m',
  35. '#^\\s*float\\((.*?)\\)\\s*$#m',
  36. '#^\\s*\[(\\d+)\\]\\s*=>\\s*$#m',
  37. '#\\s*?\\r?\\n\\s*#m',
  38. );
  39. $replace = array(
  40. 'N',
  41. 'a:\\1:{',
  42. 's:\\1:\\2',
  43. 'i:\\1',
  44. 'd:\\1',
  45. 'i:\\1',
  46. ';'
  47. );
  48. $serialized = preg_replace($regex, $replace, $str);
  49. $func = create_function(
  50. '$match',
  51. 'return "s:".strlen($match[1]).":\\"".$match[1]."\\"";'
  52. );
  53. $serialized = preg_replace_callback(
  54. '#\\s*\\["(.*?)"\\]\\s*=>#',
  55. $func,
  56. $serialized
  57. );
  58. $func = create_function(
  59. '$match',
  60. 'return "O:".strlen($match[1]).":\\"".$match[1]."\\":".$match[2].":{";'
  61. );
  62. $serialized = preg_replace_callback(
  63. '#object\\((.*?)\\).*?\\((\\d+)\\)\\s*{\\s*;#',
  64. $func,
  65. $serialized
  66. );
  67. $serialized = preg_replace(
  68. array('#};#', '#{;#'),
  69. array('}', '{'),
  70. $serialized
  71. );
  72. return unserialize($serialized);
  73. }
  74. ?>