Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(' ','&nbsp',$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?

like image 204
Roman Avatar asked Jan 18 '11 09:01

Roman


4 Answers

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)

like image 92
Jan Sverre Avatar answered Oct 10 '22 06:10

Jan Sverre


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

like image 45
moinudin Avatar answered Oct 10 '22 05:10

moinudin


always use double quotes when using \t \n etc

like image 20
Oliver M Grech Avatar answered Oct 10 '22 05:10

Oliver M Grech


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.)

like image 22
Álvaro González Avatar answered Oct 10 '22 04:10

Álvaro González