如何用PHP或CKEditor去除首尾由其生成的<p> </p>空白行?
Absolutely! You can tackle this in two effective ways—either by configuring CKEditor to avoid generating those trailing/leading blank paragraphs in the first place, or by using a regex to clean up the existing content just like PHP's trim() function. Let's walk through both options:
1. CKEditor Configuration (Prevent Blank Paragraphs at Source)
If you want to stop those empty <p> </p> lines from appearing in the output altogether, tweak these editor settings:
- Control line break behavior: Make sure your enter/shift-enter modes are set consistently to avoid accidental empty paragraphs:
CKEDITOR.config.enterMode = CKEDITOR.ENTER_P; // Default: Creates <p> on Enter CKEDITOR.config.shiftEnterMode = CKEDITOR.ENTER_BR; // Creates <br> on Shift+Enter - Remove all empty paragraphs (caution!): The
removeEmptyParagraphoption will strip out any empty<p>tags (including those with only ). But note: this removes all empty paragraphs, not just the ones at the start/end. Only use this if you don't need to keep blank lines in the middle of your content:CKEDITOR.config.removeEmptyParagraph = true;
2. Regex Solution (Precisely Trim Leading/Trailing Blank Paragraphs)
If you need to keep middle blank lines but only strip the ones at the start and end, regex is the perfect fit. Here's how to do it in PHP:
Basic Version (matches exact <p> </p> lines)
// Strip leading blank paragraphs (and any surrounding whitespace/newlines) $str = preg_replace('/^(<p> <\/p>\s*)+/', '', $str); // Strip trailing blank paragraphs (and any surrounding whitespace/newlines) $str = preg_replace('/(\s*<p> <\/p>)+$/', '', $str);
Flexible Version (handles multiple or spaces in paragraphs)
If your blank paragraphs might contain multiple spaces or characters, use this adjusted regex:
$str = preg_replace('/^(<p>( |\s)+<\/p>\s*)+/', '', $str); $str = preg_replace('/(\s*<p>( |\s)+<\/p>)+$/', '', $str);
How this works:
^anchors the match to the start of the string$anchors the match to the end of the string(<p> <\/p>\s*)+matches one or more consecutive blank paragraphs, plus any trailing whitespace/newlines between them- Replacing these matches with an empty string effectively "trims" the unwanted lines, just like
trim()does for whitespace in plain text.
内容的提问来源于stack exchange,提问作者Tech settai -
相关产品推荐
相关产品推荐

