PHP templating using custom code replacing using regex

前端 未结 4 848
暖寄归人
暖寄归人 2021-01-16 14:41

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

thanks

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 15:04

    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:

     array(
            'name' => array(
                'fullname' => 'test'
            )
        )
    );
    
    $matches = array();
    preg_match('/{\$([^.]+)\.([^.]+)\.([^}]+)}/', '{$game.name.fullname}', $matches);
    
    var_dump($matches);
    
    echo '
    '; echo $matches[1] .'
    '; echo $matches[2] .'
    '; echo $matches[3] .'
    '; echo '
    '; echo $games[$matches[1]][$matches[2]][$matches[3]]; ?>

提交回复
热议问题