Aidan's PHP Repository

A repository for PHP functions and classes ...

function.tab2space.php

Converts tabs to the appropriate amount of spaces while preserving formatting

  • Author: Aidan Lister <aidan@php.net>
  • Version: 1.2.0
  • Link: http://aidanlister.com/repos/v/function.tab2space.php
  • Return: string The text with tabs replaced
  • Views: 12343
  • Downloads: 779

Source

Download this script <?php
/**
 * Converts tabs to the appropriate amount of spaces while preserving formatting
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.2.0
 * @link        http://aidanlister.com/repos/v/function.tab2space.php
 * @param       string    $text     The text to convert
 * @param       int       $spaces   Number of spaces per tab column
 * @return      string    The text with tabs replaced
 */
function tab2space ($text, $spaces = 4)
{
    // Explode the text into an array of single lines
    $lines = explode("\n", $text);
 
    // Loop through each line
    foreach ($lines as $line) {
 
        // Break out of the loop when there are no more tabs to replace
        while (false !== $tab_pos = strpos($line, "\t")) {
 
            // Break the string apart, insert spaces then concatenate
            $start = substr($line, 0, $tab_pos);
            $tab   = str_repeat(' ', $spaces - $tab_pos % $spaces);
            $end   = substr($line, $tab_pos + 1);
            $line  = $start . $tab . $end;
        }
 
        $result[] = $line;
    }
 
    return implode("\n", $result);
}
 
?>

Example

<pre>
<?php
require_once 'function.tab2space.php';
 
$data  = "fooo\t\tbar\n";
$data .= "foooo\t\tbar\n";
$data .= "fooooo\t\tbar\n";
 
echo "This is the example data:\n";
echo $data;
echo "\n";
 
echo "With simple replace:\n";
echo str_replace("\t", "    ", $data);
echo "\n";
 
echo "With tab2space:\n";
echo tab2space($data, 8);
?>
</pre>

Output

This is the example data:
fooo		bar
foooo		bar
fooooo		bar

With simple replace:
fooo        bar
foooo        bar
fooooo        bar

With tab2space:
fooo            bar
foooo           bar
fooooo          bar

Comments

May 6th, 2005
I have rewritten the function to support multiple columns and fix some minor glitches: http://playground.jwscripts.com/tabs2spaces.phps Perhaps you can use it as a basis for other improvements.
February 11th, 2005
Muito bom = very good! ;)
February 11th, 2005
Man, you work is the best of de world! Muito bom. Thank you a lot!
January 21st, 2005
Muito bom. Thank you!
January 7th, 2005
To use this style of tabular data within HTML, simply replace the white space with Non Breaking Space like so: