使用REGEX查找PHP

Ken*_*ins 0 php regex parsing php-parser

我需要一个可以在文件中找到PHP代码块的REGEX.例如:

    <? print '<?xml version="1.0" encoding="UTF-8"?>';?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <?php echo "stuff"; ?>
    </head>
    <html>
Run Code Online (Sandbox Code Playgroud)

当REGEX解析时会返回:

array(
    "<? print '<?xml version=\"1.0\" encoding="UTF-8"?>';?>",
    "<? echo \"stuff\"; ?>"
);
Run Code Online (Sandbox Code Playgroud)

您可以假设PHP有效.

Gum*_*mbo 7

随token_get_all您获得给定PHP代码的PHP语言标记列表.然后,您只需要迭代列表,查找打开的标记令牌以及相应的关闭标记.

$blocks = array();
$opened = false;
foreach (token_get_all($code) as $token) {
    if (!$opened) {
        if (is_array($token) && ($token[0] === T_OPEN_TAG || $token[0] === T_OPEN_TAG_WITH_ECHO)) {
            $opened = true;
            $buffer = $token[1];
        }
    } else {
        if (is_array($token)) {
            $buffer .= $token[1];
            if ($token[0] === T_CLOSE_TAG) {
                $opened = false;
                $blocks[] = $buffer;
            }
        } else {
            $buffer .= $token;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 太棒了.也不知道.发现这个宝石我也很惊讶:http://www.php.net/manual/en/function.parsekit-compile-file.php (2认同)