I am looking for the best br2nl
function. I would like to replace all instances of
and <br>
with newlines <br />
\n
. Much like the nl2br() function but the opposite.
I know there are several solutions in the PHP manual comments but I'm looking for feedback from the SO community on possible solutions.
The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks. The pattern /g checks across all the string occurrences.
To do a line break in HTML, use the <br> tag. Simply place the tag wherever you want to force a line break. Since an HTML line break is an empty element, there's no closing tag.
I would generally say "don't use regex to work with HTML", but, on this one, I would probably go with a regex, considering that <br>
tags generally look like either :
<br>
<br/>
, with any number of spaces before the /
I suppose something like this would do the trick :
$html = 'this <br>is<br/>some<br />text <br />!'; $nl = preg_replace('#<br\s*/?>#i', "\n", $html); echo $nl;
Couple of notes :
<br
\s*
/
: /?
>
#i
), as <BR>
would be valid in HTMLIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With