dqybjj3497 2009-10-04 10: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 07: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部