Search code examples
phpregexprogramming-languagestemplate-engine

How can i make my own template/programming engine in php


Ive been working some time on own template engines but i alwais get stuck in strucktured documents like

<block : block1>
    <table>
        <block : row>
            <tr>
                <td>
                    {value}
                </td>
                <td>
                    {value2}
                </td>
            </tr>
        </block>
    </table>
</block>

I can get "block 1" with a regex but it will break at the first (the one of "row")

But i want a smarter way (and not by using a function like DOM) i was thinking about something like

while($i < strlen($code)){
    if(substr($code,$i,1)){
        //tag is opened
    }
}

Solution

  • Basically, you're constructing a programming language here (albeit simple, it's still a programming language). To interpret a programming language you need a compiler, which usually contains a lexer (which splits input stream into meaningful tokens) and a parser (which reads tokens one by one and takes whatever actions are needed). In your simplified example, the lexer would be probably regexp-based, and the parser can be a simple stack-based one.

    (terms in italic should actually be wikipedia links).