[英]Merge multiple HTML line breaks into one with PHP? Line-Breaks caused by P and BR tags
问题的第一部分:p标签
我有一个字符串,其中包含由p标签引起的不必要的换行符,例如:
<p>hi everyone,</p>
<p> </p>
<p> </p>
<p> </p>
<p>Here comes the content I wanted to write...</p>
我想过滤这些空的p标签并将它们合并为一个:
<p>hi everyone,</p>
<p> </p>
<p>Here comes the content I wanted to write...</p>
如何才能做到这一点?
谢谢!
第二部分问题:br标签
有时字符串包含导致换行的br标签,例如:
that is all I wanted to write.<br />
<br />
<br />
<br />
<br />
<br />
bye
这应该成为:
that is all I wanted to write.<br />
<br />
bye
尝试使用str_replace
$content = str_replace(array("<p> </p>\n", " <br />\n"), array('', ''), $content);
要使用正则表达式:
$content = preg_replace('/((<p\s*\/?>\s*) (<\/p\s*\/?>\s*))+/im', "<p> </p>\n", $content);
对于BRs
$content = preg_replace('/( (<br\s*\/?>\s*)|(<br\s*\/?>\s*))+/im', "<br />\n", $content);
编辑继承人为什么你的正则表达式工作(希望所以你可以理解它:)):
/((\\n\s*))+/im
^ ^^^ ^^ ^^^^
| \|/ || ||\|
| | || || -- Flags
| | || |-- Regex End Character
| | || -- One or more of the preceeding character(s)
| | |-- Zero or More of the preceeding character(s)
| | -- String Character
| -- Newline Character (Escaped)
-- Regex Start Character
每个正则表达式都必须以相同的字符开头和结尾。 在这种情况下,我使用了正斜杠字符。
(字符表示表达式块(要替换)换行符是\\n
。因为反斜杠用作正则表达式中的转义字符,所以需要将其转义: \\\\n
。
字符串字符是\\s
。 这将搜索一个字符串。 *
字符表示搜索前面表达式中的0个或多个,在这种情况下, search for zero or more strings: \\s*
。
+符号搜索前面表达中的一个或多个。 在这种情况下,前面的表达式是(\\\\n\\s*)
,因此只要找到一次或多次该表达式,preg_replace函数就会找到一些东西。
我使用的标志i
和m
表示case * I * nsensitive,(对于换行表达式并不是真的需要),而* M * ultiline - 意味着表达式可以遍历多行代码,而不是代码需要在一条线上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.