Intelligently removing excess indention from a string

Posted by TravisO on Stack Overflow See other posts from Stack Overflow or by TravisO
Published on 2010-05-12T22:34:39Z Indexed on 2010/05/12 22:44 UTC
Read the original article Hit count: 154

Filed under:

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?

In other words, I want to take the following

        SELECT 
            blah
        FROM
            table
        WHERE
            id=1

and convert it to

SELECT 
    blah
FROM
    table
WHERE
    id=1

here's the code I tried and fails

$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 '<pre>'. $sql .'</pre>';

© Stack Overflow or respective owner

Related posts about php