Smurof
Smurof

Reputation:

Matching contents inside php tags using regex

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().

Upvotes: 1

Views: 1233

Answers (2)

soulmerge
soulmerge

Reputation: 75704

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;
    }
}

Upvotes: 4

user142019
user142019

Reputation:

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

([.\n\r]+)

do that ^^

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

Upvotes: 0

Related Questions