Remove Line Breaks from a String in PHP

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

Table Of Contents

Background

When working with strings in PHP, especially those obtained from user inputs, file reads, or database queries, you might encounter line breaks that you need to remove. For instance, a string like “This is\na sample\r\nstring” contains line breaks (`\n` and `\r\n`), and the goal is to transform it into “This is a sample string”.

Solution 1: Using str_replace()

The str_replace() function is a straightforward way to replace all occurrences of specified characters, such as line breaks, with another character or an empty string.

Let’s see the complete example,

<?php
$originalString = "This is\na sample\r\nstring";
// Remove line breaks
$cleanString = str_replace(array("\r", "\n"), '', $originalString);

// Display the result
echo $cleanString;
?>

Output

This isa samplestring

In this example, str_replace(array(“r”, “n”), ”, $originalString) replaces all occurrences of carriage return (r) and new line (n) characters in $originalString with an empty string, effectively removing them.

Solution 2: Using preg_replace()

For more complex scenarios or patterns, you can use preg_replace() with a suitable regular expression.

Let’s see the complete example,

<?php
$originalString = "This is\na sample\r\nstring";

// Regular expression to remove line breaks
$cleanString = preg_replace('/\r\n|\r|\n/', '', $originalString);

// Display the result
echo $cleanString;
?>

Output

This isa samplestring

Here, preg_replace(‘/rn|r|n/’, ”, $originalString) uses a regular expression to match and replace carriage returns (r), new lines (n), and the combination of carriage return and new line (rn) with an empty string.

Summary

Removing line breaks from a string in PHP can be efficiently done using str_replace() for simple scenarios or preg_replace() for more complex patterns. Both methods are effective for cleaning up strings by removing unwanted line breaks, a common requirement in text processing and data manipulation tasks.

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