【发布时间】:2023-03-09 04:39:01
【问题描述】:
我正在使用所见即所得的编辑器,并且有一堆处理脏 HTML 的正则表达式。原因:我的用户经常按回车键并产生许多多余的新行,例如:
-
<br><br><br>... <p> <br /> </p><p> <br /><br /> </p><p> <br /> </p><p> &nbsp; <br /> </p><p> &nbsp; <br /> </p>- 还有更多品种,包括
p、&nbsp;和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修饰符.. -
我的理解是否正确?您想删除每个空换行符吗?
-
@AMartinNo1 是的,在用户放置多个换行符的任何地方,我都想将它们合并为 1 个换行符。问题是换行符的“结构”非常不可预测,请参见上面的示例。
-
我明白了。如果有人出于某种原因想要有多个换行符怎么办?
-
根据我几年来的经验,我可以告诉大多数用户认为换行有助于问题的视觉印象,并在问题末尾添加大约 5 - 10 个换行符,从而产生不必要的白色空间。但你是对的,我们可以允许 2 个换行符。上面的问题仍然没有解决:)