In stock PHP5, what is a good preg_replace
expression for making this transformation:
replace newlines with
, but only
Based on something SilentGhost said (which isn't showing up here for some reason):
1
2
3
< / pre>
line 1
line 2
line 3
1
2
3
< / pre>line 1
line 2
line 3
, basically. probably good enough */ $str = " ".$str; // guarantee split will be in even positions //$parts = preg_split('/()/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/", "
", $part); } } $str = implode('',$parts); /* chop off the first space, that we had added */ return substr($str,1); } assert(protect_newlines($str) === $out); ?>