NameValue.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /** @package verysimple::String */
  3. /**
  4. * A abstraction of NameValue pairs with static functions for parsing simple text structures
  5. *
  6. * @package verysimple::String
  7. * @author Jason Hinkle
  8. * @copyright 1997-2008 VerySimple, Inc.
  9. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  10. * @version 1.0
  11. */
  12. class NameValue
  13. {
  14. public $Code;
  15. public $Total;
  16. /**
  17. * Constructor optionally accepts a line that will be parsed into a name/value
  18. * @access public
  19. * @param $line the line to be parsed
  20. * @param $delim (default "=")
  21. */
  22. function __construct($line = "", $delim = "=", $nameonly=false)
  23. {
  24. $keyval = explode($delim,$line);
  25. $this->Name = $keyval[0];
  26. $this->Value = $nameonly == false && isset($keyval[1]) ? $keyval[1] : $keyval[0];
  27. }
  28. /**
  29. * Parses a string into an array of NameValue objects.
  30. * @access public
  31. * @param $lines string in the format name1=val1\nname2=val2 etc...
  32. * @param $delim the delimiter between name and value (default "=")
  33. * @param $nameonly returns only the name in the name/value pair
  34. * @return Array of NameValue objects
  35. */
  36. static function Parse($lines, $delim="=", $nameonly=false)
  37. {
  38. $return = array();
  39. $lines = str_replace("\r\n","\n",$lines);
  40. $lines = str_replace("\r","\n",$lines);
  41. $arr = explode("\n", $lines );
  42. if ($lines=="") return $return;
  43. foreach ($arr as $line)
  44. {
  45. $return[] = new NameValue($line,$delim,$nameonly);
  46. }
  47. return $return;
  48. }
  49. /**
  50. * Converts an array of NameValue objects into a simple 1 dimensional array.
  51. * WARNING: if there are duplicate Names in your array, they will be overwritten
  52. * @access public
  53. * @param $nvArray Array of NameValue objects (as returned from Parse)
  54. * @return array
  55. */
  56. static function ToSimpleArray($nvArray)
  57. {
  58. $sa = array();
  59. foreach ($nvArray as $nv)
  60. {
  61. $sa[$nv->Name] = $nv->Value;
  62. }
  63. return $sa;
  64. }
  65. }
  66. ?>