PHP templating using custom code replacing using r

2020-03-30 07:18发布

How can I convert {$game.name.fullname} to $game['name']['fullname'] using regex.

thanks

标签: php regex
4条回答
啃猪蹄的小仙女
2楼-- · 2020-03-30 07:57

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;
}
查看更多
够拽才男人
3楼-- · 2020-03-30 08:12

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]];

?>
查看更多
一夜七次
4楼-- · 2020-03-30 08:21
preg_replace(
    '/{\$([^.{}]*)\.([^.{}]*)\.([^.{}]*)}/',
    '$$1[\'$2\'][\'$3\']',
    '{$game.name.fullname}');

Edit: Edited according to ridgerunner's comment. Now matches anything between dots and matches multiple strings.

查看更多
等我变得足够好
5楼-- · 2020-03-30 08:21

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]
      )
);
查看更多
登录 后发表回答