W3docs

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.

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:

How to remove new lines from a string and replace them with a single empty space in PHP?

<?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 "

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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).

How to remove new lines from a string and replace them with a single empty space using preg_replace () function in PHP?

<?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]+/