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

时间:2013-04-05 01:00:42

标签: php regex

我正在尝试通过查找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无效,我相信我的正则表达式不会在换行后扫描。

3 个答案:

答案 0 :(得分:1)

您的示例代码错误。错误的预期结果......无论如何。使用正则表达式解析代码<?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
?>
',
)

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

我会用

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

这会不情愿地(非贪婪地)捕捉<?php?>之间的所有内容。请注意,$matches数组将嵌套。