How replace all spaces inside HTML PRE elements with
Similar to How replace all spaces inside HTML elements with  开发者_Python百科; 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 abc</pre>
<pre>123 123</pre>
$html = preg_replace(
'#(\<pre[^>]*>)(.*)(</pre>)#Umie'
, "'$1'.str_replace(' ', ' ', '$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(' ', ' ', $matches[2]).$matches[3];
}
, $html);
This requires PHP 5.3 or newer, earlier versions do not support anonymous functions.
do
$html = preg_replace('/(<pre.*>.*) (.*<\/pre>)/', '$1 $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.
精彩评论