How to replace tab with in PHP?

My database has the following text:

for x in values: print x 

I want to print this code on my HTML page. It is printed by PHP in the HTML file as it is. But when HTML is displayed by the browser, of course, I do not see the text in this form. I see the following:

 for x in values: print x 

I partially solved the problem on 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 I could solve the problem on str_replace('\t','   ',$str) . But I found out that str_replace does not recognize the space before printing as '\ t'. This space is also not recognized as just space. In other words, I do not get   before print .

Why? And how to solve the problem?

+5
source share
4 answers

You need to put \t in double quotes so that it is interpreted as a tab character. Single quotes are not interpreted.

+9
source

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, except for \' .


Old and deprecated answer:

Copy the tab character ("") from notepad, database row or this message and add this code:

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

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

+7
source

always use double quotes when using \ t \ n etc.

+3
source

This can be tricky because the tabs do not actually have a fixed size, and you will have to compute tabs. This is easier if you print the empty space as is and tell the browser to display it. You can use the <pre> tags:

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

... or set the white-space CSS property:

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

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

+3
source

Source: https://habr.com/ru/post/1335964/


All Articles