BlueNosE Posted January 12, 2008 Share Posted January 12, 2008 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? Quote Link to comment Share on other sites More sharing options...
dsaba Posted January 13, 2008 Share Posted January 13, 2008 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 Quote Link to comment Share on other sites More sharing options...
BlueNosE Posted January 13, 2008 Author Share Posted January 13, 2008 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}... Quote Link to comment Share on other sites More sharing options...
dsaba Posted January 13, 2008 Share Posted January 13, 2008 This works: ~{if cond=(.+?)}(.+?){/if}\s*(?:{else}(.+?){/else})?~si I don't see why you need * either, why would you have empty if and/or else statements? (regex)? indicates an optional subgroup (?:regex) indicates a subgroup that is not captured Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.