How to replace all XHTML/HTML line breaks (
) with new lines?

前端 未结 4 1261
死守一世寂寞
死守一世寂寞 2020-11-30 04:50

I am looking for the best br2nl function. I would like to replace all instances of
and

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 05:04

    If the document is well-formed (or at least well-formed-ish) you can use the DOM extension and xpath to find and replace all br elements by a \n text node.

    $in = '
    ...abc
    def

    ghi
    jkl

    '; $doc = new DOMDOcument; $doc->loadhtml($in); $xpath = new DOMXPath($doc); $toBeReplaced = array(); foreach($xpath->query('//br') as $node) { $toBeReplaced[] = $node; } $linebreak = $doc->createTextNode("\n"); foreach($toBeReplaced as $node) { $node->parentNode->replaceChild($linebreak->cloneNode(), $node); } echo $doc->savehtml();

    prints

    
    
    ...
    abc
    def

    ghi jkl

    edit: shorter version with only one iteration

    $in = '
    ...abc
    def

    ghi
    jkl

    '; $doc = new DOMDOcument; $doc->loadhtml($in); $xpath = new DOMXPath($doc); $linebreak = $doc->createTextNode("\n"); foreach($xpath->query('//br') as $node) { $node->parentNode->removeChild($node); } echo $doc->savehtml();

提交回复
热议问题