开发者

Replace spaces with   between PRE tags

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(' ',' ',$str);

For example, if $str cotained the following string;

<p>abc 123</p>
<pre class="abc" id="123">abcedfg 12345</pre开发者_如何学运维>

it would be converted to:

<p>abc 123</p>
<pre class="abc" id="123">abcedfg&nbsp;12345</pre>

similarly;

<p>abc 123</p>
<pre>abcedfg 12345</pre>

would be converted to:

<p>abc 123</p>
<pre>abcedfg&nbsp;12345</pre>


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(" ", "&nbsp;", $e->nodeValue);
}
echo $dom->saveHTML();

Output

<!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&nbsp;12345</pre>
<p>abc 123</p>
<pre class="abc" id="pre456">abcedfg&nbsp;12345</pre>
<div>
    <div>
        <div>
            <pre class="abc" id="pre789">abcedfg&nbsp;12345</pre>
        </div>
    </div>
</div></body></html>

EDIT:

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.


$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(" ", "&nbsp;", $matches[2])."</pre>\n";'
        ), $text);
}

echo testreplace($text);
echo testreplace($text2);

Took me a while... But it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜