如何用 替换制表符在 PHP 中?
在我的数据库中,我有以下文本:
for x in values:
print x
我想在我的 HTML 页面上打印此代码。它由 PHP 按原样打印到 HTML 文件中。但是,当浏览器显示 HTML 时,我当然不会看到这种形式的文本。我看到以下内容:
for x in values: print x
我通过 nl2br
部分解决了问题,我还使用 str_replace(' ',' ',$str)
。结果我得到:
for x in values:
print x
但我仍然需要将 print x
向右移动。我认为我可以通过 str_replace('\t',' ',$str)
解决问题。但我发现 str_replace
无法将打印之前的空格识别为“\t”。这个空间也不被认为只是一个空间。换句话说,在 print
之前我没有得到任何
。
为什么?问题又该如何解决呢?
In my database I have the following text:
for x in values:
print x
I want to print this code on my HTML page. It is printed by PHP to the HTML file as it is. But when HTML is displayed by a browser I, of course, do not see text in this form. I see the following:
for x in values: print x
I partially solved the problem by nl2br
, I also use str_replace(' ',' ',$str)
. As a result I got:
for x in values:
print x
But I still need to shift print x
to the right. I thought that I can solve the problem by str_replace('\t',' ',$str)
. But I found out that str_replace
does not recognize the space before the print as '\t'. This space is also not recognized as just a space. In other words, I do not get any
before the print
.
Why? And how can the problem be solved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
用双引号引用文本,就像这样
PHP 将解释双引号字符串中的特殊字符,而在单引号字符串中,它只会保留字符串,唯一的例外是
\'
。旧的且已弃用的答案:
从记事本、数据库字符串或这篇文章中复制制表符(“”),并添加以下代码:(
这不是四个空格,而是您从记事本复制的制表符)
Quote the text in double quotes, like this
PHP will interpret special characters in double quoted strings, while in single quoted strings, it will just leave the string, with the only exception of
\'
.Old and deprecated answer:
Copy the tab character (" ") from notepad, your databasestring or this post, and add this code:
(this is not four spaces, it is the tab character you copied from notepad)
您需要将
\t
放在双引号中,以便将其解释为制表符。不解释单引号字符串。You need to place
\t
in double quotes for it to be interpreted as a tab character. Single quoted strings aren't interpreted.使用 \t \n 等时始终使用双引号
always use double quotes when using \t \n etc
这可能很棘手,因为制表符实际上没有固定的大小,您必须计算制表位。如果按原样打印空白并指示浏览器显示它会更简单。您可以使用
...或设置
white-space
CSS 属性:(正如其他人指出的,
'\t '
与 PHP 中的"\t"
不同。)It can be tricky because tabs don't actually have a fixed size and you'd have to calculate tab stops. It can be simpler if you print blank space as-is and instruct the browser to display it. You can use
<pre>
tags:... or set the
white-space
CSS property:(As noted by others,
'\t'
is different from"\t"
in PHP.)