After I spent quite a night, trying all the above answers, I realized, for some unexpected reason, regexps did not work at all with my simple templates. They returned junk or partial information. So I decided to go by erasing all the content between tags instead of counting tags ^_^.
I mean, if a template is 'AAA {{BB}} CC {{DD}} {{BB}} SS'
, I just add '}}'
in the beginning of the template and '{{
in the end.... and all the content between }}
and {{
I'll just strip out, adding comma in between =>}}{{BB,}}{{DD,}}{{BB,}}{{
. Then - just erase }}
and {{
.
It took me about 15 min to write and test.... but with regexps I've spent about 5 hrs with no success.
/**
* deletes ALL the string contents between all the designated characters
* @param $start - pattern start
* @param $end - pattern end
* @param $string - input string,
* @return mixed - string
*/
function auxDeleteAllBetween($start, $end, $string) {
// it helps to assembte comma dilimited strings
$string = strtr($start. $string . $end, array($start => ','.$start, $end => chr(2)));
$startPos = 0;
$endPos = strlen($string);
while( $startPos !== false && $endPos !== false){
$startPos = strpos($string, $start);
$endPos = strpos($string, $end);
if ($startPos === false || $endPos === false) {
return $string;
}
$textToDelete = substr($string, $startPos, ($endPos + strlen($end)) - $startPos);
$string = str_replace($textToDelete, '', $string);
}
return $string;
}
/**
* This function is intended to replace
* //preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i',
* which did not give intended results for some reason.
*
* @param $inputTpl
* @return array
*/
private function auxGetAllTags($inputTpl){
$inputTpl = strtr($inputTpl, array('}}' => ','.chr(1), '{{' => chr(2)));
return explode(',',$this->auxDeleteAllBetween(chr(1),chr(2),$inputTpl));
}
$template = '<style>
td{border-bottom:1px solid #eee;}</style>
<p>Dear {{jedi}},<br>New {{padawan}} is waiting for your approval: </p>
<table border="0">
<tbody><tr><td><strong>Register as</strong></td><td>{{register_as}}, user-{{level}}</td></tr>
<tr><td><strong>Name</strong></td><td>{{first_name}} {{last_name}}</td></tr>...';
print_r($this->auxGetAllTags($template));
Hope it'll help somebody :)