用BR标签替换换行符,但只能在PRE标签中替换 [英] Replace newlines with BR tags, but only inside PRE tags

查看:115
本文介绍了用BR标签替换换行符,但只能在PRE标签中替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP5中,进行此转换的preg_replace表达式很好:

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

<br />替换换行符,但仅在<pre>块内

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 )

输入文字:

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

输出:

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

(激励性的上下文:试图解决Wikimedia SyntaxHighlight_GeSHI扩展中的错误20760,并发现我的PHP技能(我主要是python)并不如鼻毛.)

(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).

除regexen之外,我还接受其他解决方案,但首选small(例如,构建html解析机制是过分的.)

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

推荐答案

基于SilentGhost所说的内容(由于某些原因未在此处显示):

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) {
    // \n -> <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("/\n/", "<br />", $part);
        }
    }
    $str = implode('',$parts);
    /* chop off the first space, that we had added */
    return substr($str,1);
}

assert(protect_newlines($str) === $out);
?>

这篇关于用BR标签替换换行符,但只能在PRE标签中替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆