Remove new lines from string and replace with one empty space

Remove new lines from string and replace with one empty space

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

Stefan Bogdanescu

Founder & Senior Architect

Removing Newlines and Preserving Word Boundaries in PHP Strings

When processing text input, you often encounter strings containing multiple types of line breaks: \n, \r\n, or just \r. The goal is typically to collapse these into a single space to create a continuous flow of text. A common mistake beginners make is using the preg_replace() function immediately after constructing a regex pattern like /\r\n|\r|\n/. While that pattern correctly identifies all standard line breaks, applying it blindly often results in multiple consecutive spaces or empty strings where paragraphs used to be.

The specific requirement here is not just to remove the newlines, but to replace them with exactly one empty space. This ensures that words separated by a newline remain distinct, while also cleaning up any existing whitespace artifacts.

Why Simple str_replace Often Fails

Before diving into regular expressions, it is worth noting why a simple str_replace() loop might feel tempting but falls short in this specific scenario. If you attempt to replace \n with a space using multiple chained calls or a naive regex without careful handling of adjacent whitespace, you risk creating double spaces or leaving behind invisible characters that break layout logic later.

The regex pattern /\r\n|\r|\n/ is the gold standard for detecting these line breaks because it covers Windows (\r\n), old Mac (\r), and Linux/Unix (\n) formats in a single pass. However, the function you choose to apply this pattern depends on whether you want to maintain word boundaries or simply flatten the string completely.

Implementing preg_replace() for Consistent Results

The most robust solution in PHP is preg_replace(). This function allows you to define both a search pattern and a replacement string. By specifying ' ' (a single space) as the replacement value, you ensure that every detected line break becomes exactly one space character.

Here is how you apply it to your specific use case:

$string = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

// The regex matches \r\n, \r, or \n and replaces them with a single space.
$cleanedString = preg_replace('/\r\n|\r|\n/', ' ', $string);

echo $cleanedString; 
// Output: "put returns between paragraphs  for linebreak add 2 spaces at end "

In this example, the regex acts as a filter, scanning the entire string and swapping every instance of a newline sequence with a space. Note that if there were two newlines in a row (representing a paragraph break in your source), they would become two spaces. If strict single-spacing is required for consecutive paragraphs, an additional step to collapse multiple spaces into one might be necessary using preg_replace('/\s+/', ' ', $cleanedString).

Handling Whitespace and Edge Cases

A critical trade-off with this approach is the handling of trailing whitespace. In your source material, the string ends with a newline. Replacing that final newline with a space leaves you with a trailing space at the end of the string. While invisible to users in some contexts, this can cause issues when concatenating strings or passing data to APIs that are sensitive to trailing whitespace.

If you need to strip that final space automatically, you can chain another trim() function:

$finalString = trim(preg_replace('/\r\n|\r|\n/', ' ', $string));

This combination is often the safest bet for text normalization tasks. It guarantees that internal paragraph breaks become single spaces and removes any leading or trailing whitespace introduced by the original line breaks.

Performance Considerations

For massive text files, preg_replace() is generally efficient enough because it compiles the pattern once per execution scope in PHP 8.1+ (when using JIT) or via internal optimizations. However, if you are processing millions of lines and performance becomes a bottleneck, consider whether the regex is strictly necessary or if a simple byte-level scan could suffice. For typical web applications and string manipulation tasks though, preg_replace() offers the best balance between readability and speed.

If you are building a larger text processing pipeline in Laravel or a similar framework, you might find utility functions that abstract this logic. For instance, checking out resources like https://laravelcompany.com can provide insights into common text handling utilities often implemented in production environments, helping you avoid reinventing the wheel for standard normalization tasks.

Our network