phpnl2br

"m trying to echo a text into one line with no line breaks


I"m trying to echo a text into one line with no line breaks. I've tried to use nl2br and than replace all /n or /r with nothing. I want the output to be:

"I"m trying to write my text in one line"

instead of:

"I"m trying to write my text

in one line"

<!DOCTYPE html>
<html>
<body>

<?php

$mytext = 'I"m trying to write my text
in one line';  

$mytext = nl2br($mytext);
$mytext = preg_replace('/\r?\n|\r/','', $mytext);
$mytext = str_replace(array("\r\n","\r","\n"),"", $mytext);
echo $mytext;

?> 

</body>
</html>

Solution

  • Other than not using nl2br, and needing to replace with a space, not an empty string, your code should work fine (note you can optimise the preg_replace by using \R which matches any unicode newline sequence):

    $mytext = "I'm trying to write my text\r
    in one line";  
    
    echo preg_replace('/\R/',' ', $mytext);
    echo PHP_EOL;
    echo str_replace(array("\r\n", "\r","\n"), " ", $mytext);
    

    Output:

    I'm trying to write my text in one line
    I'm trying to write my text in one line
    

    Now if you want to make sure it remains on one line in the HTML, you need to replace spaces with non-breaking spaces e.g.

    $mytext = str_replace(' ', '&nbsp;', $mytext);
    

    Here's a demo using &nbsp; in JS:

    let str = "I'm trying to write my text in one line I'm trying to write my text in one line I'm trying to write my text in one line";
    $('#d1').html(str);
    str = str.replace(/\s/g, '&nbsp;');
    $('#d2').html(str);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="d1" style="width: 200px;"></div>
    <div id="d2" style="width: 200px;"></div>