根据 SilentGhost 所说的(由于某种原因没有出现在这里):
<?php
$str = "<div><pre class='some class' >1
2
3
< / pre>
<pre>line 1
line 2
line 3
</pre>
</div>";
$out = "<div><pre class='some class' >1<br />2<br />3<br />< / pre>
<pre>line 1<br />line 2<br />line 3<br /></pre>
</div>";
function protect_newlines($str) {
// \n -> <br />, but only if it's in a pre block
// protects newlines from Parser::doBlockLevels()
/* split on <pre ... /pre>, basically. probably good enough */
$str = " ".$str; // guarantee split will be in even positions
//$parts = preg_split('/(<pre .* pre>)/Umsxu',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
$parts = preg_split("/(< \s* pre .* \/ \s* pre \s* >)/Umsxu",$str,-1,PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $idx=>$part) {
if ($idx % 2) {
$parts[$idx] = preg_replace("/\n/", "<br />", $part);
}
}
$str = implode('',$parts);
/* chop off the first space, that we had added */
return substr($str,1);
}
assert(protect_newlines($str) === $out);
?>