tags:

views:

35

answers:

1

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 (NOTE: StackOverflow editor converted my tabs to spaces, in the code, a tab simulates 4 spaces, but it really is a \t character)

        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>';
A: 

It seems the problem was

strlen($matches[0])  

returns 0 and 1 for the first and last line, which isn't the 3 I actually wanted as the minimum, so a quick hack was to

  • trim the SQL
  • skip counting the length if it's less than 2

Not the most elegant solution, but it'll always work because tabs are usually in the 4+ count in this code. Here's the fixed 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);
    if ( strlen($matches[0]) > 1 )
    {
        $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 $sql;
TravisO