Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

newline

I am looking for the best br2nl function. I would like to replace all instances of <br> and <br /> with newlines \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.

like image 1000
markb Avatar asked Mar 12 '10 21:03

markb


People also ask

How do I replace all line breaks in a string with br /> elements?

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.

How do you force a new line in HTML?

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.


1 Answers

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>
  • or <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 :

  • starts with <br
  • followed by any number of white characters : \s*
  • optionnaly, a / : /?
  • and, finally, a >
  • and this using a case-insensitive match (#i), as <BR> would be valid in HTML
like image 162
Pascal MARTIN Avatar answered Sep 24 '22 23:09

Pascal MARTIN