Remove new lines from string and replace with one empty space

To remove new lines from a string and replace them with a single empty space in PHP, you can use the str_replace function like this:

<?php

$string = "This is a string\nwith new lines\n";
$string = str_replace("\n", " ", $string);
echo $string; // Outputs: "This is a string with new lines "

Watch a course Learn object oriented PHP

Alternatively, you can use the preg_replace function with the regular expression /\r?\n/ to match newline characters (including \r\n for Windows and \n for Unix/Linux).

<?php

$string = "This is a string\r\nwith new lines\n";
$string = preg_replace("/\r?\n/", " ", $string);
echo $string; // Outputs: "This is a string with new lines "

Note that this will replace all newline characters with a single space, regardless of how many newlines there are in a row. If you only want to replace consecutive newlines with a single space, you can use the following pattern: /[\r\n]+/