繁体   English   中英

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

[英]Merge multiple HTML line breaks into one with PHP? Line-Breaks caused by P and BR tags

问题的第一部分:p标签

我有一个字符串,其中包含由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

尝试使用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表示case * I * nsensitive,(对于换行表达式并不是真的需要),而* M * ultiline - 意味着表达式可以遍历多行代码,而不是代码需要在一条线上。

外面换行<!--?php tags</div--><div id="text_translate"><p> 我的 web 主机的 PHP 引擎将所有内容都带出 &lt;?php?&gt; 并用 &lt;br&gt; 替换换行符,如下所示:</p><pre> &lt;?php echo 'php1'; ?&gt; Hello world &lt;?php echo 'php2'; ?&gt;</pre><p> 我得到的 output 是:</p><pre> php1 &lt;br&gt;&lt;br&gt;Hello&lt;br&gt;world&lt;br&gt;&lt;br&gt;php2</pre><p> 我使用的所有其他服务器都这样做,这就是我想要的:</p><pre> php1 Hello world php2</pre><p> 我可以禁用此行为吗?</p></div>

[英]Line breaks outside <?php tags

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM