I want to parse a custom template file and still struggle with regular expressions.
I want to parse the following file:
@foreach(($ones) as $one)
@foreach($twos as $two)
multiline content
@endforeach
@endforeach
@foreach($three as $three)
@other_expression
@end_other_expression
@endforeach
The result should be:
<?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 } ?>
Replacing the @endforeach is rather easy. I did it with this code:
$pattern = '/@endforeach/'
$replacement = '<?php } ?>';
$contents = preg_replace($pattern, $replacement, $contents);
Now i need to replace the @foreach part which i tried with the following code:
$pattern = '/@foreach\(([^.]+)\)\\n/';
$replacement = '<?php foreach($1) { ?>';
$contents = preg_replace($pattern, $replacement, $contents);
The problem is that this pattern does not recognize the end of my @foreach() statement. The \n for a new line does not work. I cant use the closing bracket either because it is possible that there are multiple brackets inside the foreachhead.
Im open for any suggestion.
Thanks in advance.