使用PHP将多个HTML换行符合并为一个?由P和BR标记引起的换行符

时间:2013-05-29 08:47:28

标签: php html string filter

问题的第一部分:p tag

我有一个字符串,其中包含由p标签引起的不必要的换行符,例如:

<p>hi everyone,</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Here comes the content I wanted to write...</p>

我想过滤这些空的p标签并将它们合并为一个:

<p>hi everyone,</p>
<p>&nbsp;</p>
<p>Here comes the content I wanted to write...</p>

如何做到这一点?

谢谢!


问题的第二部分:br标签

有时字符串包含导致换行的br标签,例如:

that is all I wanted to write.<br />
<br />
&nbsp;<br />
<br />
&nbsp;<br />
<br />
bye

这应该成为:

that is all I wanted to write.<br />
<br />
bye

1 个答案:

答案 0 :(得分:3)

尝试使用str_replace

$content = str_replace(array("<p>&nbsp;</p>\n", "&nbsp;<br />\n"), array('', ''), $content);

使用正则表达式:

$content = preg_replace('/((<p\s*\/?>\s*)&nbsp;(<\/p\s*\/?>\s*))+/im', "<p>&nbsp;</p>\n", $content);

和BRs

$content = preg_replace('/(&nbsp;(<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函数就会找到一些东西。

我使用的标记im表示大小写* I * nsensitive,(换行表达式并不需要),* M * ultiline - 意味着表达式可以遍历多行代码,而不是代码需要在一行上。