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.
str_padpreg_replace_callbackandprintf, read up on those two.printfis a great idea, but the callback receives an array of matches, in other words, it would get an array of tabs without the non-whitespace characters that come after them. I suppose it might be possible to parse using the column delimiters (assuming they exist like in this particular case). Of course at that point, it would probably be easier to process the file line-by-line instead of doing a string-replace.