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

849 views Asked by At

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>
2

There are 2 answers

0
Nick On BEST ANSWER

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>

0
Kayla Fuchs On

Just preg_replace will do the trick. If the only character you need to replace is newlines, try the following:

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

Even though you don't explicitly include a newline character in your multi-line string, the line break will be interpreted as a newline character so you can identify it using \n in your regex.

The reason your current solution isn't working as expected is that nl2br inserts html line break elements into the string, not newline characters. See the docs here: https://www.php.net/manual/en/function.nl2br.php. When I run your solution it prints I"m trying to write my text<br />in one line - the newline characters are being removed, but not the html elements added by nl2br.

In the future, please include the incorrect output you're seeing in your post along with the code!