Replace spaces with   between PRE tags

前端 未结 2 847
孤城傲影
孤城傲影 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

    You can use a DOM parser. Here is how you would do it using PHP native DOM functions:

    abc 123

    abcedfg 12345

    abc 123

    abcedfg 12345
    abcedfg 12345
    '; $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();

    Output

    
    

    abc 123

    abcedfg 12345

    abc 123

    abcedfg 12345
    abcedfg 12345

    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.

提交回复
热议问题