dqybjj3497 2009-10-04 18:51
浏览 141
已采纳

用BR标签替换换行符,但仅在PRE标签内

In stock PHP5, what is a good preg_replace expression for making this transformation:

replace newlines with <br />, but only within <pre> blocks

(Feel free to make simplifying assumptions, and ignore corner cases. For example, we can assume that tags will be one line, and not pathological things like )

Input text:

<div><pre class='some class'>1
2
3
</pre>
<pre>line 1
line 2
line 3
</pre>
</div>

Output:

<div><pre>1<br />2<br />3<br /></pre>
<pre>line 1<br />line 2<br />line 3<br /></pre>
</div>

(Motivating context: trying to close out bug 20760 in a wikimedia SyntaxHighlight_GeSHI extension, and finding the my PHP skills (I mostly do python) aren't up to snuff).

I'm open to other solutions, besides regexen, but small is preferred (as an example, building html parse machinery is overkill).

  • 写回答

2条回答 默认 最新

  • dpblwmh5218 2009-10-05 15:52
    关注

    Based on something SilentGhost said (which isn't showing up here for some reason):

    <?php
    $str = "<div><pre class='some class' >1
    2
    3
    < / pre>
    <pre>line 1
    line 2
    line 3
    </pre>
    </div>";
    
    $out = "<div><pre class='some class' >1<br />2<br />3<br />< / pre>
    <pre>line 1<br />line 2<br />line 3<br /></pre>
    </div>";
    
    function protect_newlines($str) {
        // 
     -> <br />, but only if it's in a pre block
        // protects newlines from Parser::doBlockLevels()
        /* split on <pre ... /pre>, basically.  probably good enough */
        $str = " ".$str;  // guarantee split will be in even positions
        //$parts = preg_split('/(<pre .*  pre>)/Umsxu',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
        $parts = preg_split("/(< \s* pre .* \/ \s* pre \s* >)/Umsxu",$str,-1,PREG_SPLIT_DELIM_CAPTURE);
        foreach ($parts as $idx=>$part) {
            if ($idx % 2) {
                $parts[$idx] = preg_replace("/
    /", "<br />", $part);
            }
        }
        $str = implode('',$parts);
        /* chop off the first space, that we had added */
        return substr($str,1);
    }
    
    assert(protect_newlines($str) === $out);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c