An unexpected output caused by misunderstood non-greedy mode of regular expression in PHP

Recently I've been working on a PHP project with my old small framework, parts of which, including the template engine, are from Discuz!. An unexpected output from the template engine surprised me.

<?php

$input = '<html>
<table>
<thead>{loop $thread $head}<td>$head</td>{/loop}</thead>
{loop $list2 $node}
<tr>$node</tr>
{/loop}
</table>';

$output = preg_replace('/\{loop\s+(\S+)\s+(\S+)\}[\r\n\t]*(.+?)[\r\n\t]*\{\/loop\}/is', '<?php foreach(\\1 as \\2){?>\\3<?php }?>', $input);

echo htmlspecialchars($output);

$input = '<html>
<table>
<thead>{loop $thread $head}<td>$head</td>{/loop}</thead>
{loop $list2 $node}
<tr>$node</tr>
{/loop}
</table>';

echo '<br />';

$output = preg_replace('/\{loop\s+(\S+)\s+(\S+)\}[\r\n\t]*(.+)[\r\n\t]*\{\/loop\}/is', '<?php foreach(\\1 as \\2){?>\\3<?php }?>', $input);

echo htmlspecialchars($output);

?>

The situation was just like the code above. It's noticed that a non-greedy operator "?" is expected to match the first {loop $thread $head} and the first {/loop}. But unfortunately it matches the first {loop $thread $head} and the second {/loop}. Non-greedy mode seems not working. Because output1 and output2 are exactly the same.

Finally I found my solution as follows.

<?php

$input = '<html>
<table>
<thead>
{loop $thread $head}
<td>$head</td>
{/loop}
</thead>
{loop $list2 $node}
<tr>$node</tr>
{/loop}
</table>';

$output = preg_replace('/\{loop\s+(\S+)\s+(\S+)\}[\r\n\t]*(.+?)[\r\n\t]*\{\/loop\}/is', '<?php foreach(\\1 as \\2){?>\\3<?php }?>', $input);

echo htmlspecialchars($output);

?>

The non-greedy mode is kind of disordered because of the following [\r\n\t]*, which was what I didn't notice before. The regular expression engine tries to match as many as subexpressions.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值