简体   繁体   English

如何用 HTML PRE 元素替换所有空格

[英]How replace all spaces inside HTML PRE elements with  

Similar to How replace all spaces inside HTML elements with  类似于如何用   替换 HTML 元素内的所有空格using preg_replace? 使用 preg_replace?

Except I only want to modify spaces found between PRE tags.除了我只想修改 PRE 标签之间的空格。 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):将被转换为(注意 pre 标签可能包含属性,也可能不包含):

<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>
$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> .这是不贪心的,你不想替换</pre><pre>之间的空格。 Also works if the <pre></pre> section spans several lines.如果<pre></pre>部分跨越多行,也可以使用。

Note: this will fail if you have nested situations like <pre> <pre> </pre> </pre> .注意:如果你有像<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 .如果您希望能够解析它,您需要使用文档 Object Model解析 (X)HTML。

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.更新:我做了一些基准测试,结果发现回调版本每 100,000 次迭代快了大约 1 秒,所以我想我也应该提到这个选项。

$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.这需要 PHP 5.3 或更高版本,早期版本不支持匿名函数。

do
     $html = preg_replace('/(<pre.*>.*) (.*<\/pre>)/', '$1&nbsp;$2', $html, 1, $count);
while($count);

echo $html;

I'm not sure if there's a better solution.我不确定是否有更好的解决方案。 I'm not very familiar with all the preg functions.我对所有的 preg 函数都不是很熟悉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM