phphtmlregextemplates

Regex to match {@layout=xxx}


I am trying to learn the behinds of template system by creating my own and I have hit a bump...

I want to setup my template as follows:

{@layout=layoutname}

{@content}
<p>This is a paragraph</p>
{@endcontent}

But I don't know how to match {@layout= and get the layout name.

I have tried: if (preg_match('/(\{\@layout=[a-z]+\})+/', $string, $matches)) { which works ... kind of. I want to check if there are more then 1 layouts loaded to prevent errors in long files and want to count how many $matches I have and return error if more then 1 match is found but instead of getting all found layouts, it returns the same layout twice:

String used:

{@layout=app} 

{@layout=main}

{@content}
    <h1>{[username]} profile</h1>
    <img src="{[photoURL]}" class="photo" alt="{[name]}" width="100" height="100"/>
    <b>Name:</b> {[name]}<br />
    <b>Age:</b> {[age]}<br />
    <b>Location:</b> {[location]}<br />
{@endcontent}

and using that expression I get:

Array ( [0] => {@layout=app} [1] => {@layout=app} )

can someone please help me find my regex?


Solution

  • You need to use preg_match_all to get multiple matches in the same string. In this case, you want to check the $matches[1] which will be an array of capture group results. If you have more than one layout, it will have more than one element so if that's the case you know there is more than one layout declaration.

    I would also change your regex to /\{\@layout=([a-z]+)\}/ which will capture only the layout name. $matches will look like:

    array(2) {
      [0]=>
      array(1) {
        [0]=>
        string(20) "{@layout=layoutname}"
      }
      [1]=>
      array(1) {
        [0]=>
        string(10) "layoutname"
      }
    }
    

    So if count($matches[1]) > 1, you know there is more than one layout declaration. Otherwise, $matches[1][0] is your layout name.