duanpo2037 2011-07-16 07:43
浏览 281
已采纳

如何将HTML PRE元素中的所有空格替换为 

Similar to How replace all spaces inside HTML elements with   using preg_replace?

Except I only want to modify spaces found between PRE tags. For example:

<table atrr="zxzx"><tr>
<td>adfa a   adfadfaf></td><td><br /> dfa  dfa</td>
</tr></table>
<pre class="abc" id="abc">abc abc</pre>
<pre>123 123</pre>

would be converted to (note the pre tag may contain attributes, or may not):

<table atrr="zxzx"><tr>
<td>adfa a   adfadfaf></td><td><br /> dfa  dfa</td>
</tr></table>
<pre class="abc" id="abc">abc&nbsp;abc</pre>
<pre>123&nbsp;123</pre>
  • 写回答

2条回答 默认 最新

  • douxuanma4357 2011-07-16 08:15
    关注
    $html = preg_replace(
          '#(\<pre[^>]*>)(.*)(</pre>)#Umie'
        , "'$1'.str_replace(' ', '&nbsp;', '$2').'$3'"
        , $html);
    

    Has been tested, works with the sample string you provided. It's ungreedy, you don't want to replace spaces between </pre> and <pre>. Also works if the <pre></pre> section spans several lines.

    Note: this will fail if you have nested situations like <pre> <pre> </pre> </pre>. If you want to be able to parse that, you need to parse the (X)HTML using the Document Object Model.

    Update: I have done some benchmarking and it turns out the callback version is faster by about 1 second per 100,000 iterations, so I think I should also mention that option.

    $html = preg_replace_callback(
          '#(\<pre[^>]*>)(.*)(</pre>)#Uim'
        , function($matches){
              return $matches[1].str_replace(' ', '&nbsp;', $matches[2]).$matches[3];
          }
        , $html);
    

    This requires PHP 5.3 or newer, earlier versions do not support anonymous functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图