New version submitted by TomB
[carbonphp.git] / Source / carbon / libraries / Parser.php
blob7953bdc366d81466b2b101ccbf2623fb281a01ca
1 <?php
2 /*------------------------------------------------------------
3 * CarbonPHP framework (C) Tom Bell
4 * http://tombell.org.uk
5 *------------------------------------------------------------*/
7 if (!defined('CARBON_PATH'))
9 exit('Direct script access is not allowed.');
12 class Carbon_Parser
14 protected $l_delim = '{';
15 protected $r_delim = '}';
16 protected $object;
18 public function __construct()
20 log_message('debug', 'Parser.php - Carbon_Parser class initialised');
23 public function parse($template, $data, $return = false)
25 $carbon =& get_instance();
26 $template = $carbon->load->view($template, $data, true);
28 if ($template == '')
30 return false;
33 foreach ($data as $key => $value)
35 if (is_array($value))
37 $template = $this->_parse_pair($key, $value, $template);
39 else
41 $template = $this->_parse_single($key, (string) $value, $template);
45 if ($return == false)
47 $carbon->output->set_final_output($template);
50 return $template;
53 public function set_delimiters($l = '{', $r = '}')
55 $this->l_delim = $l;
56 $this->r_delim = $r;
59 protected _parse_single($key, $value, $string)
61 return str_replace($this->l_delim . $key . $this->r_delim, $value, $string);
64 protected _parse_pair($variable, $data, $string)
66 $match = $this->_match_pair($string, $variable);
68 if ($match === false)
70 return $string;
73 $str = '';
75 foreach ($data as $row)
77 $temp = $match['1'];
79 foreach ($row as $key => $value)
81 if (is_array($value))
83 $temp = $this->_parse_pair($key, $value, $temp);
85 else
87 $temp = $this->_parse_single($key, $value, $temp);
91 $str .= $temp;
94 return str_replace($match['0'], $str, $string);
97 protected _match_pair($string, $variable)
99 if (!preg_match("|".$this->l_delim . $variable . $this->r_delim."(.+)".$this->l_delim . '/' . $variable . $this->r_delim."|s", $string, $match))
101 return false;
104 return $match;