I need to extend the functionality of the following code snippet to convert spaces -only- between PRE tags in a string containing html:
str_replace(\' \',\'&
$text = '<pre>test 1234 123</pre>';
$text2 = '<pre class="test">test 1234 123</pre>';
function testreplace($text) {
return preg_replace_callback('/[\<]pre(.*)[\>](.*)[\<]\/pre[\>]/i',
create_function(
'$matches',
'return "<pre".$matches[1].">".str_replace(" ", " ", $matches[2])."</pre>\n";'
), $text);
}
echo testreplace($text);
echo testreplace($text2);
Took me a while... But it works.
You can use a DOM parser. Here is how you would do it using PHP native DOM functions:
<?php
$test = '
<p>abc 123</p>
<pre class="abc" id="pre123">abcedfg 12345</pre>
<p>abc 123</p>
<pre class="abc" id="pre456">abcedfg 12345</pre>
<div>
<div>
<div>
<pre class="abc" id="pre789">abcedfg 12345</pre>
</div>
</div>
</div>
';
$dom = new DOMDocument("1.0");
$dom->loadHTML($test);
$xpath = new DOMXpath($dom);
$pre = $xpath->query("//pre");
foreach($pre as $e) {
$e->nodeValue = str_replace(" ", " ", $e->nodeValue);
}
echo $dom->saveHTML();
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>abc 123</p>
<pre class="abc" id="pre123">abcedfg 12345</pre>
<p>abc 123</p>
<pre class="abc" id="pre456">abcedfg 12345</pre>
<div>
<div>
<div>
<pre class="abc" id="pre789">abcedfg 12345</pre>
</div>
</div>
</div></body></html>
I am not sure how to get rid of doctype/html/body tags. One possible solution that works on PHP >= 5.3.6 is to specify which node to output in the saveHTML() method. Other possibility is to use regex which I have avoided in the first place.