我正在使用所見即所得的編輯器,並且有一堆處理髒HTML的正則表達式。原因:我的用戶經常打的過於頻繁輸入鍵,產生許多新的冗餘線路,如:PHP:通過合併換行符並正確刪除空格來清理HTML
<br><br><br>
...<p> <br /> </p>
<p> <br /><br /> </p>
<p> <br /> </p>
<p> <br /> </p>
<p> <br /> </p>
- 和更多的品種包括丁
p
,
和br
這是我嘗試目前打這樣的投入,試圖合併許多連續換行到1,使用許多不同的正則表達式:
// merge empty p tags into one
// http://stackoverflow.com/q/16809336/1066234
$content = preg_replace('/((<p\s*\/?>\s*) (<\/p\s*\/?>\s*))+/im', "<p> </p>\n", $content);
// remove sceditor's: <p>\n<br>\n</p> from end of string
// http://stackoverflow.com/questions/25269584/how-to-replace-pbr-p-from-end-of-string-that-contain-whitespaces-linebrea
// \s* matches any number of whitespace characters (" ", \t, \n, etc)
// (?:...)+ matches one or more (without capturing the group)
// $ forces match to only be made at the end of the string
$content = preg_replace("/(?:<p>\s*(<br>\s*)+\s*<\/p>\s*)+$/", "", $content);
// remove sceditor's double: http://http://
$content = str_replace('http://http://', 'http://', $content);
// remove spaces from end of string ( )
$content = preg_replace('/( )+$/', '', $content);
// remove also <p><br></p> from end of string
$content = preg_replace('/(<p><br><\/p>)+$/', '', $content);
// remove line breaks from end of string - $ is end of line, +$ is end of line including \n
// html with <p> </p>
$content = preg_replace('/(<p> <\/p>)+$/', '', $content);
$content = preg_replace('/(<br>)+$/', '', $content);
// remove line breaks from beginning of string
$content = preg_replace('/^(<p> <\/p>)+/', '', $content);
我尋找新的解決方案。有什麼HTML解析器,我可以告訴合併換行符和空格?或者也許有人有另一種解決這個問題的方法。
上述的正則表達式解決方案似乎不夠合適,因爲我的用戶的換行符「嘗試」的新組合滑過。
我想在所見即所得的水平上解決這個問題。正則表達式1不需要'm'修飾符,你可能想在那裏使用's'修飾符。 – chris85
我理解你正確嗎?你想刪除每一個空行換行符? – AMartinNo1
@ AMartinNo1是的,無論用戶在哪裏放置多個換行符,我都想將它們合併爲一個換行符。問題是換行符的'結構'是相當不可預知的,請參閱上面的示例。 –