PHP templating using custom code replacing using regex

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

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

thanks

相关标签:
4条回答
  • 2021-01-16 14:59

    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;
    }
    
    0 讨论(0)
  • 2021-01-16 15:03

    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]
          )
    );
    
    0 讨论(0)
  • 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:

    <?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]];
    
    ?>
    
    0 讨论(0)
  • 2021-01-16 15:13
    preg_replace(
        '/{\$([^.{}]*)\.([^.{}]*)\.([^.{}]*)}/',
        '$$1[\'$2\'][\'$3\']',
        '{$game.name.fullname}');
    

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

    0 讨论(0)
提交回复
热议问题