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內可能有多個括號。
我打開任何建議。
在此先感謝。
這不完全的HTML,但你不應該使用正則表達式一般解析標記。這是緩慢和難以維持。 – Raziel 2015-04-03 08:26:33
什麼是替代方案? – arkhon 2015-04-03 08:46:07