How to replace tab with in PHP?
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?
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 \'
.
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)
You need to place \t
in double quotes for it to be interpreted as a tab character. Single quoted strings aren't interpreted.
always use double quotes when using \t \n etc
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>for x in values:
print x</pre>
... or set the white-space
CSS property:
div.code{
white-space: pre-wrap
}
(As noted by others, '\t'
is different from "\t"
in PHP.)
精彩评论