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 abc</pre>
<pre>123 123</pre>
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.
This requires PHP 5.3 or newer, earlier versions do not support anonymous functions.