Jump to content

Why this exp is still greedy?


BlueNosE

Recommended Posts

Hi,

I'm writing now if-else template system and i have this string:

 

{if cond=1<2}

do me (it's true)

{/if}

 

{if cond=1>2}

dont do me (it's false)

{/if}

{else}

do me (elsewise)

{/else}

 

Well, the code is:

$cnt = preg_replace ("#{if cond=(.+)}(.*){/if}\s*{else}(.*){/else}#Use", '$this->ifElseCond("\\1","\\2","\\3")', $cnt);

$cnt = preg_replace ("#{if cond=(.+)}(.*){/if}#Use", '$this->ifCond("\\1","\\2")', $cnt);

 

I'm talking only about the regexp. It have to catch every if, but the first if is catching them both and stopping only at the else.

It works great without the ifElse row. I just can't understand it - I've used the "U" modifier which have to disable this, but it does not completely work.

 

Do you know what should I do?

Link to comment
https://forums.phpfreaks.com/topic/85713-why-this-exp-is-still-greedy/
Share on other sites

expression is still greedy because you're spoiling it

haha j/k it is still greedy because you haven't made it lazy

 

.* is greedy

.*? is lazy

 

see the difference add a ? after the repetition operator +, * and it becomes lazy

 

 

when you say:

(.+)}

you realize . means match ANY character including the }, so it never stops

you match repititions of certains things like [^}]+ which is "not the } sign"

or you can make it lazy:

(.+?)}  now it will stop at the first } it reaches

 

read this tutorial:

http://www.regular-expressions.info/tutorial.html

 

 

also take out the U modifier, it behaves different with it on, try my regex tester and it will show you visually with colors where your subgroups begin and end

http://nancywalshee03.freehostia.com/regextester/regex_tester.php?seeSaved=fkfwfka2

Well ty, this tip is very useful for other problems but it didn't help me..

Look:

http://nancywalshee03.freehostia.com/regextester/regex_tester.php?seeSaved=fkfwfka2

 

Try here to put:

 

{if cond=1<2}
do me (it's true)
{/if}

{if cond=1>2}
dont do me (it's false)
{/if}
{else}
do me (elsewise)
{/else}

 

The problem is that the IF can't stop at the first time. My old code does the same thing that your code does. Your code and my code can't stop at the first {/if}...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.