如何用   替换制表符 在 PHP 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4722634/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:08:51  来源:igfitidea点击:

How to replace tab with   in PHP?

phphtmlstr-replacenl2br

提问by Roman

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:

我想在我的 HTML 页面上打印此代码。它由 PHP 按原样打印到 HTML 文件中。但是当浏览器显示 HTML 时,我当然看不到这种形式的文本。我看到以下内容:

for x in values: print x

I partially solved the problem by nl2br, I also use str_replace(' ','&nbsp',$str). As a result I got:

我部分解决了这个问题nl2br,我也使用str_replace(' ','&nbsp',$str). 结果我得到:

for x in values:
print x

But I still need to shift print xto the right. I thought that I can solve the problem by str_replace('\t','   ',$str). But I found out that str_replacedoes 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.

但我仍然需要print x向右移动。我以为我可以通过str_replace('\t','   ',$str). 但我发现str_replace无法将打印前的空格识别为 '\t'。这个空间也不被认为只是一个空间。换句话说,我 print.

Why? And how can the problem be solved?

为什么?如何解决问题?

回答by moinudin

You need to place \tin double quotes for it to be interpreted as a tab character. Single quoted strings aren't interpreted.

您需要\t用双引号将其解释为制表符。不解释单引号字符串。

回答by Jan Sverre

Quote the text in double quotes, like this

用双引号引用文本,像这样

str_replace("\t", '    ', $str);

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 \'.

PHP 会解释双引号字符串中的特殊字符,而在单引号字符串中,它只会保留字符串,唯一的例外是\'.



Old and deprecated answer:

旧的和已弃用的答案:

Copy the tab character (" ") from notepad, your databasestring or this post, and add this code:

从记事本、数据库字符串或这篇文章中复制制表符 (" "),然后添加以下代码:

str_replace('   ','    ',$str);

(this is not four spaces, it is the tab character you copied from notepad)

(这不是四个空格,是你从记事本复制的制表符)

回答by álvaro González

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:

这可能很棘手,因为制表符实际上没有固定大小,您必须计算制表位。如果按原样打印空格并指示浏览器显示它,则可能会更简单。您可以使用<pre>标签:

<pre>for x in values:
   print x</pre>

... or set the white-spaceCSS property:

...或设置white-spaceCSS 属性:

div.code{
    white-space: pre-wrap
}

(As noted by others, '\t'is different from "\t"in PHP.)

(正如其他人所指出的,'\t'"\t"PHP不同。)

回答by Oliver M Grech

always use double quotes when using \t \n etc

使用 \t \n 等时总是使用双引号