如何让Summernote生成的HTML代码恢复可读性并避免重复换行?
Hey there! Let's tackle this problem from two angles: fixing your existing HTML with PHP without getting duplicate line breaks, and configuring Summernote to output nicely formatted HTML right from the start so you don't have to fix it later.
The issue with your initial string replacement is that it keeps adding newlines every time you save—so after the second save, you end up with double newlines, then triple, etc. The fix is to first normalize your HTML (strip any existing extra whitespace around closing tags) before adding consistent newlines.
Option 1: Regex (Simple Scenarios)
This works well for basic HTML like your example:
// Your input HTML (could be from database or file) $html = '<h1>Title</h1><p>Some text</p><p>Some text</p>'; // Step 1: Remove all whitespace (newlines, spaces, tabs) around closing tags $cleaned = preg_replace('/\s*<\/([^>]+)>\s*/', '</$1>', $html); // Step 2: Add a single newline after every closing tag $formatted = preg_replace('/<\/([^>]+)>/', '</$1>' . PHP_EOL, $cleaned); // Output: // <h1>Title</h1> // <p>Some text</p> // <p>Some text</p>
By stripping existing whitespace first, you ensure that every closing tag starts fresh before adding a newline—no duplicates, no matter how many times you run this.
Option 2: DOMDocument (More Reliable for Complex HTML)
Regex can break if your HTML has unusual cases (like attributes with > characters). For production use, use PHP's built-in DOM parser to safely format HTML:
$html = '<h1>Title</h1><p>Some text</p><p>Some text</p>'; $dom = new DOMDocument(); // Disable automatic <html>/<body> tags and preserve existing structure $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $formatted = $dom->saveHTML();
This will give you properly indented, readable HTML with consistent line breaks—no risk of regex edge cases.
Why fix it after the fact when you can make Summernote output formatted HTML from the start? Summernote doesn't have built-in HTML formatting, but you can pair it with a lightweight front-end library like js-beautify to handle this automatically.
- First, add
js-beautifyto your page (you can include it via CDN or local file). - Configure Summernote's
onSavecallback to format the HTML before saving:
$('#summernote').summernote({ height: 300, // Adjust as needed callbacks: { onSave: function() { // Get raw HTML from Summernote const rawHtml = $(this).summernote('code'); // Format with js-beautify const formattedHtml = beautify.html(rawHtml, { indent_size: 2, // Use 2-space indentation preserve_newlines: true, wrap_line_length: 0 // Disable line wrapping if preferred }); // Update Summernote with formatted HTML $(this).summernote('code', formattedHtml); } } });
Now, every time you save (or trigger the save event), Summernote will output clean, readable HTML—no backend processing required.
If you don't want to add an extra library, you can enable Summernote's code view (add code to your toolbar) and let users format HTML manually, but automatic formatting is obviously more user-friendly.
Hope one of these solutions works for you!
内容的提问来源于stack exchange,提问作者Gimbo

