I need to display a plain-text file that contains two-space tab’d columns of data in a web page.
What I did was to use PHP to read the text file and print it out between <pre> tags to use a monospace font as so:
<pre>
<?php
$fn="data.txt";
$fi=fopen($fn, "r");
$fc=fread($fi, filesize($fn)); //open and read text file
fclose($fi);
$fc=str_replace("\t", " ", $fc); //replace tabs with two spaces
print($fc); //print data between PRE tags
?>
</pre>
It almost works, but the tabs are being troublesome. It is trivial to replace the tabs with two spaces, but then non-whitespace characters are pushed over instead of absorbed into the tabs. True tabs absorb n-1 non-whitespace characters (where n is the number of spaces per tab).
For example, the following table should be displayed as so:
| | 43| 43| 7| | |
| 12|128|128|128| | 53|
| 3| 3| 3| 3| | |
| | | 21| 21| 39| |
However by blindly replacing all tabs with two-spaces, we get this:
| | 43| 43| 7| | |
| 12|128|128|128| | 53|
| 3| 3| 3| 3| | |
| | | 21| 21| 39| |
I’m trying to figure out a (reasonably easy) way to convert the tabs to spaces while accounting for tabs that don’t take up the full n spaces.
I have written this function some time ago, might be helpful:
It was meant to deal with multibyte strings, if you have only numbers, you can get rid of
mb_, it will speed up this function.[+] Note that this is meant to work with one line, so you will need to process line by line with
fgetsinstead of whole file at once.