开发者

Render tab characters in HTML [duplicate]

开发者 https://www.devze.com 2022-12-27 03:11 出处:网络
This question already has answers here: Encoding a tab in html [duplicate] (4 answers) Closed 8 years ago.
This question already has answers here: Encoding a tab in html [duplicate] (4 answers) Closed 8 years ago.

I have to render some text to a web page. The text is coming from sources outside my control and it is formatted using newlines and tab charact开发者_如何学JAVAers.

New lines (\n) can be replaced by br tags, but what about preserving tabs? A brief search reveals there is no way to directly render tab characters in HTML.


Why not just wrap the content in a <pre> tag? This will handle the \n as well as the \t characters.


An alternative to the non-breaking space would be the em space (&emsp; or &#x2003;). It is usually rendered as a longer space, if that is an advantage.


A Quick & Dirty Way

For a quick fix, you can use the xmp tag to stop the browser from collapsing whitespace. The xmp tag contains text that should be rendered uninterpreted (and in a monospaced font).

The problem is that xmp tags have been deprecated since HTML3.2, and have been dropped from the HTML5 spec altogether. In practice, browsers still support xmp tags, so they can still be useful, but not in production.

The Proper Way

Tabs are for tabulating data. The proper way to tabulate data in HTML is to use the table tag. Every line in your original string translates to a row in the table, while each tab in the original string starts a new (left-aligned) cell in the table.

Imagine you had this (tab-aligned) string to begin with:

Spam    1.99
Cheese  2.99

Translated to HTML, that string would look like this:

<table>
    <tr> <td> Spam   </td> <td> 1.99 </td> </tr>
    <tr> <td> Cheese </td> <td> 2.99 </td> </tr>
</table>

Note: If you wrapped the tab-aligned string in xmp tags and styled the HTML table to look like plain text, the rendered results would be the same.


replace \t with &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.

Each space you want will be a &nbsp;

As pointed out this isn't completely correct as it only pretends to be a tab as HTML doesn't actually output format a tab as you would expect.


If you're already replacing line breaks, why not do the same for tabs...?

str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $text);


&emsp;, &ensp;, &#8195; or &#8194; can be used.

W3 says little about this...

The character entities &ensp; and &emsp; denote an en space and an em space respectively, where an en space is half the point size and an em space is equal to the point size of the current font. 

Read More at W3.org fro HTML3

Read More at W3.org for HTML4

Even more at Wikipedia (about spaces)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号