How do I keep whitespace formatting using PHP/HTML?

the <pre> and </pre> might not be ideal in textarea etc..

When wanting to preserve new line - \n and \n\r use nl2br as mentioned by UnkwnTech and Brad Mace.

When wanting to preserve spaces use str_replace:

str_replace(' ', '&nbsp;', $stringVariable);

When both use this:

$result = str_replace(' ', '&nbsp;', $stringVariable);
$result = nl2br($result);

use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space

<pre>
text goes here and here 
             and here and here            Some out here
     ▄             ▄█▄ █▄       ▄
 ▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀    ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀
██  ██ ▀██▄▄ ▄█  ▀ ░▒ ░▒   ██  ██ ▄█▄ █▀ ██
█▓▄▀██  ▄ ▀█▌▓█    ▒▓ ▒▓   █▓▄▀██ ▓█ ▀▄  █▓
█▒  █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█   █▒  █▓ ▒█  ▓█▄ ▒
    ▀▒           ▀  ▀ █▀       ▀▒  ▀  █▀  ░

</pre>  

You might have to convert any <'s to &lt; 's


For all those searchng for preserving the text fetched from database , this worked for me , setting CSS as following ,

pre {
     white-space: pre-line;
     text-align : left;
  }

in html :

<pre >
     <?php echo htmlentities($yourText ) ; ?>
</pre>

When you print the data use nl2br() to convert \n and \r\n into <br>

Tags:

Html

Php

Ascii