1

{$thisname} should be converted to <?php echo $thisname; ?>.

{thisname} should be converted to <?php echo $thisname; ?>.

{$this.movie.games} && {$this.new} should be converted respectively to <?php echo $this["movie"]["games"]; ?> and <?php echo $this["new"]; ?>.

4 Answers 4

1
$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"]; ?>
Sign up to request clarification or add additional context in comments.

Comments

1

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 :)

1 Comment

I didn't downvote, but adding a huge templating system just to be able to do this kind of replacement may not be what the user wants or needs. (On the other hand, on second thought, it may save the OP a ton of work, especially when it comes to parsing complex stuff like var1.var2.var3 so +1)
0

Use the str_replace function.

1 Comment

That replaces all the } tags with ; ?> which i dont want to do...I wanted to use preg match
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.