Roman
Roman

Reputation: 131128

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?

Upvotes: 6

Views: 31317

Answers (4)

Jan Sverre
Jan Sverre

Reputation: 4713

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)

Upvotes: 12

Álvaro González
Álvaro González

Reputation: 146460

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

Upvotes: 3

Oliver M Grech
Oliver M Grech

Reputation: 3171

always use double quotes when using \t \n etc

Upvotes: 3

moinudin
moinudin

Reputation: 138357

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

Upvotes: 10

Related Questions