Home Β» Php Β» How do I keep whitespace formatting using PHP/HTML?

How do I keep whitespace formatting using PHP/HTML?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains ASCII art and whatnot that I would like to preserve. When I print out the string on the HTML page, even if it does have the same formatting and everything since it is in HTML, the spacing and line breaks are not preserved. What is the best way to print out the text in HTML exactly as it was in the original text file?
I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor πŸ˜›
Basically, I would like suggestions on how to display ASCII art in HTML.

How to&Answers:

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

Answer:

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);

Answer:

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

Answer:

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>

Answer:

just echo the necessary special characters (\s, \n, or \r ) along with your string in your PHP code.

<?php 

echo ("hello world \n")

?>