@forelse regex parser
% php test.php
string(235) "
<h1>Users:</h1>
<?php $__x = User::all(); ?>
<?php if ($__x && is_array($__x) && count($__x)): ?>
<?php foreach ($__x as $user): ?>
{{ $user->name }}
<?php endforeach; ?>
<?php else: ?>
<p>There are no users</p>
<?php endif; ?>
"
string(256) "
<h1>Users:</h1>
<?php $__x = $users; ?>
<?php if ($__x && is_array($__x) && count($__x)): ?>
<?php foreach ($__x as $user): ?>
<span class="name">{{ $user->name }}</span>
<?php endforeach; ?>
<?php else: ?>
<p>There are no users</p>
<?php endif; ?>
"
<?php
function convert($in) {
return preg_replace('/@forelse\s+\((.*)\s+as\s+(.*)\)\s+(.*)\s+@empty\s+(.*)\s+@endforelse/', '<?php $__x = $1; ?>
<?php if ($__x && is_array($__x) && count($__x)): ?>
<?php foreach ($__x as $2): ?>
$3
<?php endforeach; ?>
<?php else: ?>
$4
<?php endif; ?>
', $in);
}
var_dump(convert('
<h1>Users:</h1>
@forelse (User::all() as $user)
{{ $user->name }}
@empty
<p>There are no users</p>
@endforelse
'));
var_dump(convert('
<h1>Users:</h1>
@forelse ($users as $user)
<span class="name">{{ $user->name }}</span>
@empty
<p>There are no users</p>
@endforelse
'));