Handling (expanding) tabs in PHP
Archive - Originally posted on "The Horse's Mouth" - 2010-10-29 08:08:08 - Graham EllisQuestion - Is a tab 8 spaces or 4?
Answer - Not quiet either, really. It's a movement of the cursor forward by up to 8 spaces (or 4 spaces or some other number if you have altered your tab stops).
We have many sample programs and data files on our web site (there's a full list, together with all related longer and shorter articles [here]), and they contain something of a mixture of tabs and spaces ... and that (together with the browser's behaviour of compressing multiple white space) leads to some very badly formatted displays unless specific correctional action is taken.
• We display sample source code in a fixed width font, and with <pre> tag, or by specifying pre in the white-space property in CSS (and selecting a fixed width font there too).
• We replace tabs with the appropriate number of spaces in our display scripts - here's the course code to handle a line of text in PHP:
while (($posn = strpos($line,"\t")) !== false) {
$spaces = 8 - ($posn % 8) ;
$line = substr_replace($line,str_repeat(" ",$spaces),$posn,1);
}
With many file formats, spaces can be interchanged with tabs with little problem, but there are exceptions - the makefile uses the tab character as a delimiter and spaces won't do ... I recall printcap files used to have problems if you used the wrong character, and Python programs that inlcude a mix of tabs and spaces can be very confusing if you rad them with an editor set to none-8 tab spacing. And of course they are vitally important in tab separated value files (.tsv's) of the sort that you'll often use when you export data from a program like Microsoft Excel.