How can I convert {$game.name.fullname} to $game[\'name\'][\'fullname\'] using regex.
thanks
This tested function has the (commented) regex you want:
function process_data(&$text)
{
$re = '/# Reformat a string.
\{ # Opening delimiter.
(\$\w+) # $1: game.
\. # Parts separated by dot.
(\w+) # $2: name.
\. # Parts separated by dot.
(\w+) # $3: fullname.
\} # Closing delimiter.
/ix';
$text = preg_replace($re, "$1['$2']['$3']", $text);
return $text;
}
If you are asking how to convert a string like "{mario.jumper.two}" to a php array like $game['mario']['jumper']='two'
$input="{mario.jumper.two}"
$input=str_replace( array('{','}') , '' ); //strip out brackets
$inputArray=explode('.',$input) // creates array( 'mario','jumper','two')
$game=array(
$inputArray[0] => array(
$inputArray[1] => $inputArray[2]
)
);
If you are asking how to replace {$game.name.fullname} with the value of $game['name']['fullname'], my first suggestion would be not to allow the template to include any old variable (you don't want access to vars like $secret_password), but make an array of values that can be included.
Take a look at this:
<?php
$games = array(
'game' => array(
'name' => array(
'fullname' => 'test'
)
)
);
$matches = array();
preg_match('/{\$([^.]+)\.([^.]+)\.([^}]+)}/', '{$game.name.fullname}', $matches);
var_dump($matches);
echo '<hr/>';
echo $matches[1] .'<br/>';
echo $matches[2] .'<br/>';
echo $matches[3] .'<br/>';
echo '<hr/>';
echo $games[$matches[1]][$matches[2]][$matches[3]];
?>
preg_replace(
'/{\$([^.{}]*)\.([^.{}]*)\.([^.{}]*)}/',
'$$1[\'$2\'][\'$3\']',
'{$game.name.fullname}');
Edit: Edited according to ridgerunner's comment. Now matches anything between dots and matches multiple strings.