drpsrvu85668 2016-07-21 02: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 08: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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画