I am looking for the best br2nl function. I would like to replace all instances of and
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
defghi
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
defghi
jkl
edit: shorter version with only one iteration
$in = '
... abc
defghi
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();