tags:

views:

192

answers:

2

Hi,

I have some trouble matching the contents inside php tags.

Currently I have this code, but it's not working for me:

<?php preg_match_all('/<\?php(.+)\?>/', $str, $inside_php); ?>

I need to retrieve the contents so I can do other things with them, like eval().

A: 

a period (or dot) does not match new lines:

([.\n\r]+)

do that ^^

<?php preg_match_all('/<\?php([.\n\r]+)\?>/', $str, $inside_php); ?>
Time Machine
That didn't work for me, but thanks anyway :)
Smurof
+4  A: 

Stop right there, you don't want to do it this way!

You can use the tokenizer extension of PHP to break a string into tokens, which will reliably find all PHP source code. Then you can do whatever transformation you want with the tokens. Regular expressions are not the tool for this job (You don't want to put out the fire with a spoon, do you?)

$tokens = token_get_all($string);
foreach ($tokens as $token) {
    if (is_array($token)) {
        if (!in_array($token[0], array(T_INLINE_HTML, T_OPEN_TAG, T_CLOSE_TAG))) {
            echo $token[1];
        }
    } else {
        echo $token;
    }
}
soulmerge
Or have you already taken short tags into account? Or opening php tags in strings?
soulmerge
Sorry I missed out on your answer. Thanks a bunch, this is awesome!
Smurof
Theres a type on line 4, I believe $oken[0] should be $token[0]. Once again thank you, this has helped me out bigtime!
Smurof
glad to help, fixed typo.
soulmerge