[英]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.