replace tags with PHP variables using preg_match

前端 未结 4 1653
误落风尘
误落风尘 2020-12-22 03:13

{$thisname} should be converted to .

{thisname} should be converted to

相关标签:
4条回答
  • 2020-12-22 03:42

    Use a templating system, I suggest using http://phpsavant.com/ although it looks like you're more interested in Smarty or Dwoo

    There's no need to re-invent the wheel :)

    0 讨论(0)
  • 2020-12-22 03:50

    Use the str_replace function.

    0 讨论(0)
  • 2020-12-22 03:57
    $tpl = 'Name: {$name}, Surname: {surname}, City: {$person.address.city}';
    
    function tpl2php($m){
        $var =  $m[1];
        if(strpos($var,'.')){
            $varArr = explode('.',$var);
            $var = $varArr[0];
            for($i=1;$i<count($varArr);$i++){
                $var .= '["' . $varArr[$i] .'"]';
            }
        }
        return '<?php echo $' . $var . '; ?>';
    }
    
    $php = preg_replace_callback('/{\$?([_a-z][\w\.]+[\w])}/iS','tpl2php',$tpl);
    // Name: <?php echo $name; ?>, Surname: <?php echo $surname; ?>, City: <?php echo $person["address"]["city"]; ?>
    
    0 讨论(0)
  • 2020-12-22 03:59

    preg_replace and regular expressions are more flexible than str_replace, especially if you have to parse a string like this.movie to $this["movie"]. It will not be an easy task though.

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