簡體   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