如何用新行替换所有XHTML/HTML换行符(< br>)? [英] How to replace all XHTML/HTML line breaks (<br>) with new lines?
问题描述
我正在寻找最好的br2nl
功能.我想用换行符\n
替换<br>
和<br />
的所有实例.与 nl2br()函数非常相似,而相反.
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.
我知道PHP手册注释中有几种解决方案,但是我正在寻找SO社区对可能解决方案的反馈.
I know there are several solutions in the PHP manual comments but I'm looking for feedback from the SO community on possible solutions.
推荐答案
我通常会说"不要使用正则表达式来处理HTML ",但是在这一点上,我可能会去使用正则表达式时,考虑到<br>
标签通常看起来像这样:
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/>
,在/
之前具有任意数量的空格
<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;
笔记夫妇:
- 以
<br
开头
- 后跟任意数量的白色字符:
\s*
- 可选地,一个
/
:/?
- 最后是一个
>
- ,并且使用不区分大小写的匹配项(
#i
),因为<BR>
在HTML中有效
- 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
这篇关于如何用新行替换所有XHTML/HTML换行符(< br>)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!