drpsrvu85668 2016-07-20 18:33
浏览 81
已采纳

PHP-REGEX - 在pre标签内用<br>替换换行符

I have

<pre>
Line one
Line two
Line three
Line four
Line five
Line six
</pre>

If I strip the pre tags, it becomes

Line one Line two Line three Line four Line five Line six

What would be the regex for replacing new lines with a br so that after stripping pre tag each line is separate.

  • 写回答

1条回答 默认 最新

  • doubi1713 2016-07-21 00:11
    关注

    At each position you need to check whether or not you are inside a valid <pre> tag:

    ~(?s)(?<!<pre>)\R(?!</pre>)(?=((?!<pre>).)*</pre>)~
    

    Explanation:

    (?s)                # Set DOT_ALL modifier
    (?<!<pre>)          # Assert if we are not immediately after an opening <pre> tag
    \R                  # We need new-lines only
    (?!</pre>)          # Not followed by a closing </pre> tag
    (?=                 # Beginning of a positive lookahead
        ((?!<pre>).)*   # To look if we are not behind an opening <pre> tag (inside a <pre> tag)
        </pre>          # Which has a closing </pre> tag
    )                   # End of lookahead
    

    Live demo

    Note: It doesn't provide expected results if you have nested <pre> tags (!)

    But if you are comfortable to work with DOM then there is a more suitable solution for this:

    <?php
    
    $html = <<< HTML
    <div>
    <div>
    test
    test
    test
    </div>
    <pre>
    Line one
    Line two
    Line three
    Line four
    Line five
    Line six
    </pre>
    </div>
    HTML;
    
    $dom = new DOMDocument;
    @$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED  | LIBXML_HTML_NODEFDTD);
    $preTags = $dom->getElementsByTagName('pre');
    
    foreach ($preTags as $key => $pre) {
        $pre->nodeValue = str_replace(PHP_EOL, '~*~*', $pre->nodeValue);
    }
    
    echo str_replace("~*~*", '<br />', $dom->saveHTML());
    

    Output:

    <div>
    <div>
    test
    test
    test
    </div>
    <pre><br />Line one<br />Line two<br />Line three<br />Line four<br />Line five<br />Line six<br /></pre>
    </div>
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部