Remove all line breaks from a String in PHP

This article, will discuss multiple ways to remove all line breaks from a string in PHP.

Table Of Contents

Background

Removing line breaks from a string is a common requirement in PHP, especially when processing text data, formatting output, or preparing strings for web display.

For example, if you have the following multi-line string:

"This is a sample\nstring with some\nline breaks.";

You aim to transform it into a single-line string:

"This is a sample string with some line breaks."

Let’s look at some methods to accomplish this.

Solution 1: Using str_replace()

The str_replace() function is used to replace all occurrences of a search string in a string with a replacement string. We can use it to replace line break characters with an empty string.

Let’s see the complete example,

<?php
$originalString = "This is a sample\nstring with some\nline breaks.";

// Remove all line breaks
$singleLineString = str_replace(["\r\n", "\n", "\r"], '', $originalString);

echo $singleLineString;
?>

Output

This is a samplestring with someline breaks.

In this code:
– We replace all types of line break characters (rn, n, r) with an empty string (”).
– str_replace() will remove all occurrences of line break characters, resulting in a single-line string.

Solution 2: Using preg_replace()

For a more robust solution that can handle different types of newline characters, you might use preg_replace() with a regular expression.

Let’s see the complete example,

<?php
$originalString = "This is a sample\nstring with some\nline breaks.";

// Regular expression pattern to match all types of line breaks
$pattern = '/\r\n|\r|\n/';

// Remove all line breaks
$singleLineString = preg_replace($pattern, '', $originalString);

echo $singleLineString;
?>

Output

This is a samplestring with someline breaks.

In this code:
– The regular expression pattern /(rn|r|n)/ matches all types of line breaks (rn, n, r).
– preg_replace() replaces these matched line break characters with an empty string.
– This method is particularly useful when dealing with strings that may contain different types of line breaks.

Summary

To remove all line breaks from a string in PHP, both str_replace() and preg_replace() are effective methods. str_replace() is a straightforward approach when you know the exact types of line breaks you want to remove, while preg_replace() offers a more comprehensive solution for handling various line break formats. The choice between them depends on your specific needs and the nature of your input string.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top