Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('#<brs*/?>#i', "
", $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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...