How to Transform a String from Multi-Line to Single-Line in PHP?

Solution:1

Line conversion techniques

Approach 1

To remove anything unnecessary between the closing and opening </p>…<p> tags you can use a regular expression. I haven’t cleaned it up so it’s just for reference.

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

It will strip anything between the p tags, such as newlines, whitespace or any text.

Approach 2

And again with the delete-only-linebreaks-and-newlines approach

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

Approach 3

Or with the somewhat faster but inflexible simple-string-replacement approach

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

Take a pick!

Comparison

Let’s compare my methods

Performance

Performance is always relative to the fastest approach in this case the second one.

(Lower is better)

Approach 1   111
Approach 2   300
Approach 3   100

Result

Approach 1
Strips everything between tags

Approach 2 and 3
Strips newline and linebreak characters

Solution:2

The best method I found to make a multi-line string a single line was like this

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

This is similar to other answers but adds “\r\n”, which must be the initial part of the array, so that it doesn’t double up.