| | > PHP Fun, Continued (Automatically cross-posted from CodewiseBlog.)Okay, I'm a moron. I
spent a ton of time trying to write out a regular expression which
would match an infinitely nested set of if/else/end tags in my skin
sets. That didn't work at all. I then spent a ton of time trying to write a recursive function to do the same. That worked even less well. Then, while trying to find out why my recursive regular expression didn't work (damn you "(?R)"
!!), it came to me like a blinding light from heaven. ZOMG! Why didn't
I think of this earlier?! Write a regular expression that finds the
innermost set of if/else/end tags, process those, then repeat until
there's nothing left. Brilliant I say! Well, it would've been brilliant
if I had actually thought to do that in the first place instead of
wasting an hour and a half in utter feutility. The golden code: *a heavenly chorus sings*
<?php
$ifcapture = "<\\!-- #cwb_if# (?P<condition>(?:.(?!-->))+) -->"; $if = "<\\!-- #cwb_if# ((?:.(?!--))+) -->"; $else = "<\\!-- #cwb_else# -->"; $end = "<\\!-- #cwb_endif# -->"; $pattern = "/$ifcapture(?P<true>(?>.(?!$if))*?)($else(?P<false>(?>.(?!$if))*?))?$end/s";
/* ** Here, we work on the innermost set of tags first. ** The regex only matches sets of tags that have no #cwb_if# tags inside. ** We keep re-evaluating the regex until there are no tags left. ** You don't want to know how long it took to work this out... :P */
preg_match_all($pattern, $skin, $matches, PREG_SET_ORDER); do { foreach($matches as $match) { $old = $match[0]; $condition = $match["condition"]; $true = $match["true"]; $false = $match["false"];
$result = eval("return " . voodoo($condition, $args, $skin_section, FALSE) . ";");
if($result) { $skin = str_replace($old, voodoo($true, $args), $skin); } else { $skin = str_replace($old, voodoo($false, $args), $skin); } }
preg_match_all($pattern, $skin, $matches, PREG_SET_ORDER); } while(count($matches) > 0);
?>
voodoo()
is the function that does all the processing of the tags, and is in
itself a recursive function because that's where this code is located.
Not so complex as what I was trying to do earlier, though. Comment here or directly at CodewiseBlog. |
| | Posted 10/17/2005 9:17 PM - 15 Views - 2 eProps - 1 Comment
- recommend
    - recs0
- share
- email
 - sent0
Give eProps or Post a Comment |