Skip to content

All topics  /  PHP

How to String Replace Newline With Space in PHP?

PHP ·

Hi Dev,

This article will provide example of How to string replace newline with space. In this article, we will implement a remove line breaks from the string in php. I explained simply about replace newline char by space. you will learn replace newlines with br tag and trim whitespaces in php. Let's see bellow example remove line breaks with php.

Example 1


index.php

<?php
    $string = "This\r\nis\n\ra\nstring\r";
    echo nl2br($string);
?>

Output:

This<br/>
is<br/>
a<br/>
string

Example 2

index.php

<?php
    $lines = "Welcome\rHello\nPHP\r\n";
    $nl = ["\r\n","\n","\r"];
    echo str_replace($nl, '<br>', $lines);
?>

Output:

Welcome
Hello
PHP

I hope it could help you...