How to replace tab with   in PHP?
Asked Answered
F

4

6

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?

Ferreira answered 18/1, 2011 at 9:52 Comment(2)
Why not putting the text to be displayed inside a <pre> tag?Rudiment
php.net/types.string <- a text that every PHP developer should learn by heartCawley
G
12

Quote the text in double quotes, like this

str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $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('   ','&nbsp;&nbsp;&nbsp;&nbsp;',$str);

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

Gosport answered 18/1, 2011 at 9:59 Comment(0)
L
10

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

Laflam answered 18/1, 2011 at 9:58 Comment(0)
D
3

always use double quotes when using \t \n etc

Dalston answered 18/1, 2011 at 9:59 Comment(0)
E
3

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

Envoy answered 18/1, 2011 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.