2015-04-03 55 views
0

我想解析一个自定义模板文件,仍然难以用正则表达式。preg在php中用自定义标记替换

我想解析以下文件:

@foreach(($ones) as $one) 

    @foreach($twos as $two) 

     multiline content 

    @endforeach 

@endforeach 

@foreach($three as $three) 

    @other_expression 

    @end_other_expression 

@endforeach 

结果应该是:

<?php foreach(($ones) as $one) { ?> 

    <?php foreach ($twos as $two) { ?> 

     multiline content 

    <?php } ?> 

<?php } ?> 

<?php foreach($threes as $three) { ?> 

    @other_expression 

    @end_other_expression 

<?php } ?> 

更换@endforeach是相当容易的。

$pattern = '/@endforeach/' 
$replacement = '<?php } ?>'; 
$contents = preg_replace($pattern, $replacement, $contents); 

现在我需要更换,我试着用下面的代码@foreach部分:我这个代码做了

$pattern = '/@foreach\(([^.]+)\)\\n/'; 
$replacement = '<?php foreach($1) { ?>'; 
$contents = preg_replace($pattern, $replacement, $contents); 

的问题是,这种模式不承认结束我的@foreach()语句。新行的\ n不起作用。我无法使用右括号,因为foreachhead内可能有多个括号。

我打开任何建议。

在此先感谢。

+0

这不完全的HTML,但你不应该使用正则表达式一般解析标记。这是缓慢和难以维持。 – Raziel 2015-04-03 08:26:33

+0

什么是替代方案? – arkhon 2015-04-03 08:46:07

回答

2

您可以使用正则表达式2在连续做这样的:

<?php 
    $str = "@foreach((\$ones) as \$one)\n\n @foreach(\$twos as \$two)\n\n  multiline content\n\n @endforeach\n\[email protected]\n\[email protected](\$three as \$three)\n\n @other_expression\n\n @end_other_expression\n\[email protected]>"; 
    $result = preg_replace("/\\@endforeach/", "<?php } ?>", preg_replace("/\\@foreach(.*)/", "<?php foreach$1 { ?>", $str)); 
    print $result; 
?> 

输出:

<?php foreach(($ones) as $one) { ?>                                                      

    <?php foreach($twos as $two) { ?>                                                     

     multiline content                                                        

    <?php } ?>                                                           

<?php } ?>                                                            

<?php foreach($three as $three) { ?>                                                     

    @other_expression                                                         

    @end_other_expression                                                        

<?php } ?>