问题的第一部分:p tag
我有一个字符串,其中包含由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
答案 0 :(得分:3)
尝试使用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
表示大小写* I * nsensitive,(换行表达式并不需要),* M * ultiline - 意味着表达式可以遍历多行代码,而不是代码需要在一行上。