How do I remove blank lines from text in PHP?

How do I remove blank lines from text in PHP?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Your Regex for Removing Blank Lines Fails in PHP

You are attempting to strip empty lines from a text string, but your current approach using ereg_replace or preg_replace isn't delivering the expected result. The core issue lies in how regular expressions interpret line endings and anchors. When you use a pattern like '^[ \t]*$', you are correctly matching lines that start with optional whitespace and end immediately. However, the placement of this pattern within the replacement logic is where the logic breaks down for multi-line strings.

The anchor character ^ asserts the start of a string or line, while $ asserts the end. In many regex engines, including PCRE (used by preg_replace), these anchors behave differently depending on whether the /m (multiline) flag is set. Without this flag, ^ only matches the very beginning of the entire string, and $ only matches the very end of the entire string. Consequently, a pattern designed to match every blank line inside a paragraph will fail if it relies solely on these anchors without the multiline modifier.

To successfully remove blank lines containing only whitespace in PHP, you must adjust both the regex syntax and the flags. The most robust solution involves using preg_replace with the /s (DOTALL) flag or, more commonly for line-based operations, ensuring the pattern correctly targets the newline characters associated with those empty lines.

Consider the following input string:

$str = "blahblah\r\n\nblahblah\r\n   adsa \r\n\r\nsad asdasd";

Your goal is to collapse consecutive blank lines into a single line break while preserving intentional single-line breaks. A simple replacement of ^[ \t]*$ against the whole string without flags will leave most blank lines untouched. Instead, you need to target the newline sequences that immediately follow a line consisting entirely of whitespace or nothing at all.

A more effective regex pattern focuses on matching the newline character itself when it is preceded by optional whitespace and the end of a line. The pattern /\n+/ combined with logic to check preceding content can work, but a cleaner approach often targets the specific structure: a line with only spaces/tabs followed by a newline.

Here is a functional implementation using preg_replace:

$str = "blahblah\r\n\nblahblah\r\n   adsa \r\n\r\nsad asdasd";

// Remove lines that are empty or contain only whitespace, collapsing multiple breaks into one
$result = preg_replace('/^[ \t]*\r?\n/', '', $str, -1, PREG_REPLACE_ALL); 

Wait, strictly speaking, simply removing the line break might collapse too much. If you want to keep one line break between paragraphs but remove blank lines, you should match a newline only if the preceding line was empty. However, standard practice for this specific requirement often involves matching the sequence of whitespace followed by newlines that represent empty lines and replacing them with a single newline or nothing depending on strictness.

If your goal is simply to delete the blank lines entirely so that blahblah sits directly above blahblah, you can use a pattern that matches a line consisting of only whitespace (or nothing) followed by a newline:

$str = "blahblah\r\n\nblahblah\r\n   adsa \r\n\r\nsad asdasd";

// Match start of line, optional spaces/tabs, end of line, and the newline sequence
$result = preg_replace('/^[ \t]*\r?\n/', '', $str);

This approach assumes the multiline context is handled by how PHP processes strings or by ensuring the pattern applies per-line logic. A safer bet that guarantees the anchor ^ works for every line within the string is to use the /m flag:

$result = preg_replace('/^[ \t]*\r?\n/', '', $str, -1, PREG_REPLACE_ALL); 
// Actually, simpler with /m flag:
$result = preg_replace('/^[ \t]*\r?\n/m', '', $str);

Wait, preg_replace in PHP does not automatically enable multiline mode for anchors unless you pass the /m modifier. If you omit it, ^ matches only the start of the string. Therefore, the correct invocation requires the flag:

$str = "blahblah\r\n\nblahblah\r\n   adsa \r\n\r\nsad asdasd";
$result = preg_replace('/^[ \t]*\r?\n/', '', $str, -1, PREG_REPLACE_ALL); 
// Correction: The /m flag is required for ^ and $ to work per-line.
$result = preg_replace('/^[ \t]*\r?\n/m', '', $str);

Without the /m flag, your original code failed because it tried to match empty lines at the start of every line but could only find one at the actual start of the string (if any). By adding the m modifier (or using PREG_OFFSET_CAPTURE logic if needed), the anchors correctly identify every blank line within the text block.

This distinction is critical when processing large logs or user inputs where line structure matters. If you are working within a Laravel application, ensure you are passing raw strings to these functions and not letting helper methods strip necessary characters prematurely. For more complex text normalization tasks, consider leveraging Laravel's Str facade which offers cleaner abstractions for string manipulation, though for pure regex needs, native PHP functions remain the most direct tool.

Always verify the output against edge cases, such as a file ending with a newline or lines containing only tabs. The pattern ^[ \t]* correctly handles both spaces and tabs, ensuring no hidden characters slip through your filter.

Our network