How can I convert a multi-line string into a single-line string in PHP?

Solution 1: Line Conversion Techniques

You can remove unnecessary content or line breaks between HTML

tags using several approaches.

Approach 1: Remove Anything Between

Tags Using Regex


$str = preg_replace("/(\/[^>]*>)([^<]*)(<)/", "\\1\\3", $str);

This strips anything between closing and opening

tags, including newlines, whitespace, or text.

Example:


<p>Text</p>
<p>More text</p>

Approach 2: Remove Only Line Breaks and Newlines Using Regex


$str = preg_replace("/[\r\n]*/", "", $str);

Approach 3: Remove Line Breaks Using str_replace()


$str = str_replace(array("\r","\n"), "", $str);

Solution 2: Convert a Multi-line String into a Single Line

The simplest and most reliable way to remove all line breaks and make a string a single line is using


str_replace():

$newstring = str_replace(array("\r\n", "\n", "\r"), '', $oldstring);

Notes:

The order matters: “\r\n” should come first to avoid double replacements.

This approach removes all types of line breaks (Windows, Unix, and Mac style) in one step.

It’s simple, fast, and avoids regex overhead.