Replace spaces with   between PRE tags

前端 未结 2 848
孤城傲影
孤城傲影 2021-01-23 10:41

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(\' \',\'&         


        
相关标签:
2条回答
  • 2021-01-23 11:25
    $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 讨论(0)
  • 2021-01-23 11:25

    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.

    0 讨论(0)
提交回复
热议问题