Page 1 of 1

Fixing regexp to get code between <? ... ?>

Posted: Sun Aug 02, 2009 11:41 am
by ben.artiss
Hi everyone,

I'm trying to get the code between <?(php) ... ?> tags and kind seem to get the solution. The expression I have at the moment (from here) is:

Code: Select all

$exp = '<\?

Code: Select all

*([^\?>]*)\?>';
- but it doesn't seem to work (the [] aren't allowed). Does anyone know how to correct it?

Thanks in advance for any help (sorry I'm terrible at regexp!).

Regards, Ben

Re: Fixing regexp to get code between <? ... ?>

Posted: Sun Aug 02, 2009 12:31 pm
by jackpf
Just for clarification - do you mean <?(php) ?> or <?php ?>?

Re: Fixing regexp to get code between <? ... ?>

Posted: Sun Aug 02, 2009 3:14 pm
by ben.artiss
I was thinking of making an allowance to cater for both situations, in case someone enters <? instead of <?php - the idea came from this date check function I came across:

Code: Select all

# d(d)?m(m)?y(yyy)
$pattern = '(^[0-9]{1,2})'
         . '([^0-9a-zA-Z])'
         . '([0-9]{1,2})'
         . '([^0-9a-zA-Z])'
         . '([0-9]{1,4}$)';
 
if (ereg($pattern, $input, $regs)) {
    return validate::verify_date($regs[1], $regs[3], $regs[5]);
}
I'm using this for the time being but it only caters for <?php:

Code: Select all

function getCodeBetweenTags($input) {
    $pattern = '^<\?php(.*?)\?>^';
    preg_match($pattern, $input, $regs);
    return  isset($regs[1]) ? $regs[1] : NULL;
} // getCodeBetweenTags()
I'm sure there's only something small to add but I'm a bit stumped! :) Thanks for the response.

Re: Fixing regexp to get code between <? ... ?>

Posted: Sun Aug 02, 2009 3:50 pm
by jackpf
Try this:

Code: Select all

/\<\?(php)?(.*?)\?\>/is
That's PCRE btw, none of that ereg crap :P

Re: Fixing regexp to get code between <? ... ?>

Posted: Sun Aug 02, 2009 4:50 pm
by ben.artiss
Brilliant that's the one, thanks for your help jackpf! :D

Re: Fixing regexp to get code between <? ... ?>

Posted: Mon Aug 03, 2009 7:14 am
by jackpf
Cool.

No problem.

You do understand it right? Knowing regex is such a useful skill...I was just wondering if you actually understood it. In case you don't, basically, the ? means that php is optional. So it will work with <? and <?php.

Re: Fixing regexp to get code between <? ... ?>

Posted: Mon Aug 03, 2009 3:41 pm
by ben.artiss
Hehe I understand it when I see it but to come up with it is sometimes confusing! But that's a big help - I'm startin to get the grasp of the preg functions now :) thanks man.