如何使用 PHP/HTML 保持空白格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I keep whitespace formatting using PHP/HTML?
提问by Steven Oxley
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 artand 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 HTMLexactly 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 :P
Basically, I would like suggestions on how to display ASCII art in HTML.
我正在解析文件中的文本并将其存储在字符串中。问题是原始文件中的一些文本包含ASCII art我想保留的内容。当我打印出 上的字符串时HTML page,即使它确实具有相同的格式和所有内容,因为它在 中HTML,间距和换行符也不会保留。HTML完全按照原始文本文件中的文本打印文本的最佳方法是什么?
我想举一个例子,但不幸的是,我无法在这个 Markdown 编辑器中正确显示它:P
基本上,我想就如何显示ASCII art in HTML.
回答by Grant
use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space
使用 <pre> 标签(预格式化),它将使用单行字体(用于您的艺术)并保留所有空白
<pre>
text goes here and here
and here and here Some out here
▄ ▄█▄ █▄ ▄
▄█?█▓ ▄▓??█? ???█▓?? ?? ▄█?█▓?????▓▄?██??
██ ██ ?██▄▄ ▄█ ? ?? ?? ██ ██ ▄█▄ █? ██
█▓▄?██ ▄ ?█▌▓█ ?▓ ?▓ █▓▄?██ ▓█ ?▄ █▓
█? █▓ ██▄▓? ?█▄▄█▄▓█ ▓█ █? █▓ ?█ ▓█▄ ?
?? ? ? █? ?? ? █? ?
</pre>
You might have to convert any <'s to < 's
您可能需要将任何 < 转换为 < 的
回答by Igor L.
the <pre>and </pre>might not be ideal in textarea etc..
在<pre>和</pre>在文本区域等可能不是很理想..
When wanting to preserve new line - \nand \n\ruse nl2bras mentioned by UnkwnTech and Brad Mace.
如果想保存新的生产线-\n和\n\r使用nl2br由UnkwnTech和布拉德·梅斯提及。
When wanting to preserve spaces use str_replace:
当想要保留空间使用str_replace:
str_replace(' ', ' ', $stringVariable);
str_replace(' ', ' ', $stringVariable);
When both use this:
当两者都使用这个时:
$result = str_replace(' ', ' ', $stringVariable);
$result = nl2br($result);
回答by UnkwnTech
回答by Divyanshu Jimmy
For all those searchng for preserving the text fetched from database , this worked for me , setting CSS as following ,
对于所有搜索保留从数据库中获取的文本的人来说,这对我有用,将 CSS 设置如下,
pre {
white-space: pre-line;
text-align : left;
}
in html :
在 html 中:
<pre >
<?php echo htmlentities($yourText ) ; ?>
</pre>
回答by tut
just echo the necessary special characters (\s, \n, or \r ) along with your string in your PHP code.
只需在 PHP 代码中回显必要的特殊字符(\s、\n 或 \r)以及您的字符串即可。
<?php
echo ("hello world \n")
?>

