Question

str = "I am  So        Coool       Because I    can do stuff            Like THIS!";

I used the php function nl2br() to show the text as like the same in text area.

echo nl2br(str)

It is replacing the space between the So and Coool,I and can,stuff and Like from the above example.

Output i am getting is I am So Coool Because I can do stuff Like THIS!

Expecting is I am So Coool Because I can do stuff Like THIS!

How to show the paragraph text along with spaces.

Was it helpful?

Solution 2

Spaces are compacted in HTML because there's a distinction between how HTML is formatted and how it should be rendered. You can use pre tag to show your text as is. for example try to use

echo '<pre>'.$str.'</pre>';

OTHER TIPS

This is caused by browser wrapping.

To show multiple spaces within HTML you have few options:

A - Wrap your code in <pre> element

<pre><?php echo $text; ?></pre>

B - Add white-space: pre to parent element (W3Schools)

.text-wrapper {
   white-space: pre;
}

C - Replace spaces with &nbsp;, (this in non-breaking whitespace - your text will not wrap from spaces)

<?php echo str_replace(' ', '&nbsp;', $text); ?>

It seems that the browser is the issue here since all the spaces are in the html code.

Try it with <pre></pre> tags

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top