需要通过查找PHP标记拆分带有换行符的字符串


Need to split a string with line breaks by finding PHP tags

我试图通过寻找PHP标签来拆分带有换行符的字符串。

这是我到目前为止的代码:

$contents = '
some test
some more test
test 1
<?php 
test 2 and test 4
test 6
?>
test 7
test 9
<?php 
test 10
test 12
>?
test 13
<?php test 14
test 16 
?>
test 17
';

可以看出,PHP代码是EVEN测试示例,ODD测试示例在PHP标记之外。

我要做的是提取到数组php代码的每次迭代:

预期结果:

array(
    [0] =>  <?php 
            test 2 and test 4
            test 6
            ?>
    [1] =>  <?php 
            test 10
            test 12
            >?
    [2] =>  <?php test 14
            test 16 
            ?>
)

我已经尝试用结束标签preg_split,然后用开始标签捕获$explode[1],但我的代码是错误的…

$ends = preg_split("/[?>]/s", $contents, PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE );
print_r($ends);
foreach($ends as $flufcode){
  $trimcode = explode('<?php', $flufcode);
  echo $trimcode . " next:";
}

到目前为止,我的preg_split不工作,我相信我的regex在换行后没有扫描。

您的示例代码是错误的。错误的预期结果……无论如何。使用正则表达式解析代码,如<?php echo '?>'; ?>将失败。

为了正确而简单的解析,您应该使用token_get_all。给你的例子。

$tokens = token_get_all($contents);
$catch = false;
$codes = array();
$index = 0;
foreach ($tokens as $token)
    {
    if (is_array($token) && $token[0] == 'T_OPEN_TAG)
        {
        $catch = true;
        $index++;
        $codes[$index] = '';
        }
    if ($catch)
        $codes[$index] .= is_array($token) ? $token[1] : $token;
    if (is_array($token) && $token[0] == 'T_CLOSE_TAG)
        {
        $catch = false;
        }
    }
var_export($codes);

将根据您提供的数据生成。

array (
  1 => '<?php
test 2 and test 4
test 6
?>
',
  2 => '<?php
test 10
test 12
>?
test 13
<?php test 14
test 16
?>
',
)

问号是一个正则表达式元字符——尝试转义:

$ends = preg_split("/''?>/sm", $contents, PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE );

我会用

preg_match_all("/<'?php.*?'?>/s", $contents, $matches);

不情愿地(不是贪婪地)捕获<?php?>之间的所有内容。注意,$matches数组将被嵌套。