IEnumerable
IEnumerable

Reputation: 3790

Regular Expression for a condition

I am building a HTML template system, I need to allow the users to add condition as shown below.

example of the if condition;

..HTML...
[if:UserLevel > 100]
    ...conditional HTML...
[endif]
...More HTML....

I am in need of a PHP Regular Expression that matches;

[if:$]
   $
[endif]

where $ if variable/wildcard.

Upvotes: 0

Views: 132

Answers (2)

Qtax
Qtax

Reputation: 33908

"/\[if:([^]]+)](.*?)\[endif]/s"

Will do what you asked for.

Note that just using plain regex like this for your templating is not an effective approach, and will not even work in some cases. For example you cannot nest these if statements when parsting them with such a regex.

There are many templating languages out there, I suggest you have a look at some of them. (Unless you are only doing this for educational purposes.)

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

preg_match("(\[if:([^]+])\](.*?)\[endif\])is",$data);

The s modifier allows for there to be newlines in your input data.

If you capture the match, $match[1] will be the condition, and $match[2] the HTML inside it.

Upvotes: 1

Related Questions