4

UPDATE

So I am still messing with this, and have gotten as far as finding all the instances of tags, though I'd rather JUST find the deepest stacked instance, as life would be easier that way.. Anyway here is what I got..

/(({{)(?:(?=([^\/][^ ]*?))\3|(\/[\w])))([a-zA-Z0-9\$\'\"\s\#\%\^\&\!\.\_\+\=\-\\\*\(\)\ ]+?}})/

Are there ANY regexp guru's out there that could give me some pointers or a regexp that mimics what I need? Which is only getting the deepest stacked instance of a {{tag}} that ends like this {{//tag}}

ORIGINAL

Ok, so I have an issue I have seen others have, but with a different approach to it.. Or so I thought.. So I am curious if anyone else can help me solve this issue further..

I have a database full of templates that I need to work with in PHP, these templates are made and used by another system, and so there for can not be changed. With that said, these templates have hierarchy style tags added to them. What I need to do, is get these templates from the database, and then programmatically find these tags, their function name (or tag name), and their inner contents, as well as anything following the function (tag) name within the brackets.. An example of one of these tags is, {{FunctionName some (otherStuff) !Here}} Some content sits inside and it ends {{/FunctionName}}

This is where it gets more fun, the templates have another random tag, which I am guessing are the "variable" style of these tags, as they are always generally the same syntax. Which looks like this, ${RandomTag}, but also there are times that the function style one is there but without an ending tag, like so.. {{RandomLoner}}

Example Template...

{{FunctionTag (Condition?)}}
    <div>This is an {{CheckOfSomeSort someTimesThese !orThese}}
        example of some {{Random}} data
    {{/CheckOfSomeSort}} that will be ${worked} on</div>
{{/FunctionTag}}

Ok so in no way is this a real template, but it follows all the rules that I have seen thus far.

Now I have tried different things with regex and preg_match_all to pull out the matches, and get each of these into a nice array. So far what I have got is this (used it on the example template to make sure its working still)

Array
(
    [0] => Array
        (
            [0] => {{CheckOfSomeSort someTimesThese !orThese}}example of some datas{{/CheckOfSomeSort}}
            [1] => {{CheckOfSomeSort someTimesThese !orThese}}
            [2] => CheckOfSomeSort
            [3] => example of some data
            [4] => {{/CheckOfSomeSort}}
        )
)

I have tried a couple approaches, (that took me nearly 8 hours to get to)

/({{([^\/].[^ ]*)(?:.[^ ][^{{]+)}})(?:(?=([^{{]+))\3|{{(?!\2[^}}]*}}))*?({{\/\2}})/

AND, more recently...

/({{([^\/].[^ ]*)(?:.[^ ][^{{]+)}})((?:(?!\{\{|\}\}).)++|(?R)*)({{\/\2}})/

In no way am I a guru with regexp, I actually just learned it over the last day or so, trying to get this to work. I have googled for this, and realize that regexp is not designed for nested stuff, but the (?R) seems to do the trick on simple bracket examples Ive seen on the internets, but they always only take into account of the stuff between the { and } or ( and ) or < and >. After reading nearly the whole regex info website, and playing, I came up with these 2 versions.

So what I NEED to do (I think), would have a regexp work from the DEEPEST hierarchy tag first, and work its way out (if I can do that with help from php, thats fine with me). I was thinking finding the Deepest layer, get its data, and work backwards til all the contents are in 1 fat array. I assumed that was what the ($R) was going to do for me, but it didn't.

So any help on what I am missing would be great, also take into note that mine seems to have issues with {{}} that DONT have an ending version of it. So like my {{Random}} example, was removed for the sake of me parsing the array example. I feel these tags, along with the ${} tags can be left alone (if I knew how to do that with regexp), and just remain in the text where they are. I am more or less interested in the functions and getting their data into a multidimensional array for me to work with further.

Sorry for the long post, I just have been banging me head all night with this. I started with the assumption that it was going to be a bit easier.. Til I realized the tags where nested :/

Any help is appreciated! Thanks!

9
  • I know it's a no-no (and terrible performance-wise) but if this is just something you need to accomplish once you could always just do a preg_match to get the outermost "tag" and then do further preg_match calls on that tag's contents. Might be easier than trying to create a single monolithic regex.
    – rdlowrey
    Jan 13, 2012 at 19:23
  • @rdlowrey will not yield the same result for nested tags... consider simple example {{foo}}hello world {{foo}} goodbye {{/foo}}{{/foo}}
    – Kaii
    Jan 13, 2012 at 19:24
  • For starters, { and } are special within regexes and you need to escape them -- not that it helps, it makes matters even more complicated :p Just a "side remark"... Reading further.
    – fge
    Jan 13, 2012 at 19:24
  • 1
    Also, I think the regex you listed up there just got loose and ate some small children for breakfast.
    – rdlowrey
    Jan 13, 2012 at 19:24
  • @Kaii I was just trying to say that it might be simpler to break the problem space up into smaller, more solvable problems ... not so much saying "do this exactly". I probably should have been more clear.
    – rdlowrey
    Jan 13, 2012 at 19:26

3 Answers 3

1

Wow, what a strange templating syntax.

The method I would probably use to tackle this problem would be something like:

  • Use a simple regex to change all the {{tags}} to <tags>
  • Use another simple regex to convert the space-delimited arguments/conditions inside tags to XML-like attribute syntax (ex. {{foo bar !baz}} would become <foo arg1="bar" arg2="!baz"> or similar)
  • Process it as a DOMDocument.

Have fun. :-)

1
  • Hmm, I appreciate this suggestion, though I havn't really used the "DOMDocument" before.. Guess after figuring out regexp overnight, it would't hurt to dive into some more new stuff though :P It does kind of scare me though, as I am not wanting to screw up the intact html in any way, in the end the html and the tagged data need to be separated..
    – NinjaKC
    Jan 13, 2012 at 19:50
0

Warning! You are trying to write a parser with just regular expressions. That doesn't work very well. Why not? Because you need to store state as well!

So what then? Well, you write a parser of course :D

If you need any tips on how to get started I can help but I'd encourage you to try it by yourself first. How does a parser work anyway? :)


Tokenize your input. And transform it to a nested tree like so:

array(
    array("code", "FunctionTag (Condition?)", array(
        "<div>This is an ",
        array("code", "CheckOfSomeSort someTimesThese !orThese", array(
            "example of some ",
            array("code", array("Random"), array()),
            " data"
        )),
        " that will be ${worked} on</div>"
    ))
)

Now you just have to interpret the code parts and produce the expected output. You could also add things like line numbers and character positions which is very useful for debugging.

1
  • Hate to say it, but yes, a parser it is.. But I am not writing it for the same cause as the rest of the world, which is where it becomes an issue, as it will probably only ever be used for this case.. On either note, tips would be great.. like I laid out, I have the concept, just need to figure out where I am going wrong.. I feel like I am using both cases properly, and even running them through a function to strip whats been found.. just it doesn't continue after the first tag it finds it seems.. I want all the deep tags first, than remove them, back out, and continue the loop..
    – NinjaKC
    Jan 13, 2012 at 19:36
-1

After a bit of time working on it, I ultimately learned more about regex, and understand it to a T now. Great thing about this, is that PHP has the (?R) and I now understand why it even looks like this. lol

In the end, the regex that I got working spawned off the php page that explained the recursive (?R). I then just worked on getting the tags regex in place of the parenthesis they were using in the example.

I know I wanted the inner most tag, but ofcourse can accomplish the same thing with the outermost tag, so this regex does just that. It finds and grabs the outer most {{tag (thatMightHaveDataHere)}} And has inner contents that may be more {{TAGS}} within it.{{/tag}}

Here it is,

/{{([\w]+) ?([^}]*?)(?:}}((?:[^{]*?|(?R)|{{[\w]*?}}|\${.*?})*){{\/\1}})/ 

0 = Matched "Outer Tag" 1 = Tag that was found, ie {{tag}}{{/\1}} 2 = Any data after the first space, within the tag, ie {{tag ThisDataIs StoredAs2}} 3 = INNER Content (which can be the recursive of this regex, or a non ended tag {{noEndTag}}, or a tag that starts with a dollar ${likeThis}

Run a loop on the $match[3] with this regex, and you can cycle through finding them. Not sure where you would use this outside what I needed it for, but I am sure someone can modify it if they need it to work on some other nested style structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.