You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP或CKEditor去除首尾由其生成的<p>&nbsp;</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>&nbsp;</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 removeEmptyParagraph option will strip out any empty <p> tags (including those with only &nbsp;). 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>&nbsp;</p> lines)

// Strip leading blank paragraphs (and any surrounding whitespace/newlines)
$str = preg_replace('/^(<p>&nbsp;<\/p>\s*)+/', '', $str);

// Strip trailing blank paragraphs (and any surrounding whitespace/newlines)
$str = preg_replace('/(\s*<p>&nbsp;<\/p>)+$/', '', $str);

Flexible Version (handles multiple &nbsp; or spaces in paragraphs)

If your blank paragraphs might contain multiple spaces or &nbsp; characters, use this adjusted regex:

$str = preg_replace('/^(<p>(&nbsp;|\s)+<\/p>\s*)+/', '', $str);
$str = preg_replace('/(\s*<p>(&nbsp;|\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>&nbsp;<\/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 -

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:02:07