Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This turned out not so straightforward but hopefully this could be helpful to others. The biggest complication was returning non-string from callback function of preg_replace.</p> <p>Thanks all who tried to help!</p> <pre><code>class Parser { public $ret=array(); function loadTemplateFromString($str){ $this-&gt;parsed_template=$this-&gt;tags=array(); if(!$str){ return; } var_dump($str); /* First expand self-closing tags &lt;?$tag?&gt; -&gt; &lt;?tag?&gt;&lt;?/tag?&gt; */ $str=preg_replace('/&lt;\?\$([\w]+)\?&gt;/','&lt;?\1?&gt;&lt;?/\1?&gt;',$str); /* Next fix short ending tag &lt;?tag?&gt; &lt;?/?&gt; -&gt; &lt;?tag?&gt; &lt;?/?&gt; */ $x=preg_replace_callback('/.*?&lt;\?\/\?&gt;/',function($x){ return preg_replace('/(.*&lt;\?([^\/][\w]+)\?&gt;)(.*?)(&lt;\?\/?\?&gt;)/', '\1\3&lt;?/\2?&gt;',$x[0]); },$str); /* Finally recursively build tag structure */ $this-&gt;recursiveReplace($x); } function recursiveReplace($x){ if(is_array($x)){ // Called recursively $tmp2=$this-&gt;ret;$this-&gt;ret=array(); }else{ $x=array(4=&gt;$x); $tmp2=null; } $y=preg_replace_callback('/(.*?)(&lt;\?([^\/$][\w]+)\?&gt;)(.*?)(&lt;\?\/(\3)?\?&gt;)(.*?)/', array($this,'recursiveReplace'),$x[4]); $this-&gt;ret[]=$y; if($tmp2===null)return; $tmp=$this-&gt;ret; $this-&gt;ret=$tmp2; $this-&gt;ret[]=$x[1]; $this-&gt;ret[]=$tmp; return ''; } } $p=new Parser(); $p-&gt;loadTemplateFromString('bla &lt;?name?&gt; name &lt;?/name?&gt; bla bla &lt;?$surname?&gt; bla '. '&lt;?middle?&gt; mm &lt;?/?&gt; blah &lt;?outer?&gt; you &lt;?inner?&gt; are &lt;?/?&gt; inside &lt;?/outer?&gt;'. ' bobobo'); var_dump($p-&gt;ret); </code></pre> <p>This outputs:</p> <pre><code>array 0 =&gt; string 'bla ' (length=4) 1 =&gt; array 0 =&gt; string ' name ' (length=6) 2 =&gt; string ' bla bla ' (length=9) 3 =&gt; array 0 =&gt; string '' (length=0) 4 =&gt; string ' bla ' (length=5) 5 =&gt; array 0 =&gt; string ' mm ' (length=4) 6 =&gt; string ' blah ' (length=6) 7 =&gt; array 0 =&gt; string ' you ' (length=5) 1 =&gt; array 0 =&gt; string ' are ' (length=5) 2 =&gt; string ' inside ' (length=8) 8 =&gt; string ' bobobo' (length=7) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload