Intelligently removing excess indention from a string
<p>I'm trying to remove some excessive indention from a string, in this case it's SQL, so it can be put into a log file.  So I need the find the smallest amount of indention (aka tabs) and remove it from the front of each line, but the following code ends up printing out exactly the same, any ideas?</p>

<p>In other words, I want to take the following (NOTE: StackOverflow editor converted my tabs to spaces, in the code, a tab simulates 4 spaces, but it really is a \t character)</p>

<pre><code>        SELECT 
            blah
        FROM
            table
        WHERE
            id=1
</code></pre>

<p>and convert it to</p>

<pre><code>SELECT 
    blah
FROM
    table
WHERE
    id=1
</code></pre>

<p>here's the code I tried and fails</p>

<pre><code>$sql = '
        SELECT 
            blah
        FROM
            table
        WHERE
            id=1
';

// it's most likely idented SQL, remove any idention
$lines = explode("\n", $sql);
$space_count = array();
foreach ( $lines as $line )
{
    preg_match('/^(\t+)/', $line, $matches);
    $space_count[] = strlen($matches[0]);
}

$min_tab_count = min($space_count);

$place = 0;
foreach ( $lines as $line )
{
    $lines[$place] = preg_replace('/^\t{'. $min_tab_count .'}/', '', $line);
    $place++;
}

$sql = implode("\n", $lines);

print '&lt;pre&gt;'. $sql .'&lt;/pre&gt;';
</code></pre>
