Skip to content

Instantly share code, notes, and snippets.

@lolandese
Last active October 1, 2019 15:14
Show Gist options
  • Select an option

  • Save lolandese/413a2bd16a17bc2fa0ee2fdaf284ec20 to your computer and use it in GitHub Desktop.

Select an option

Save lolandese/413a2bd16a17bc2fa0ee2fdaf284ec20 to your computer and use it in GitHub Desktop.
Removes excessive indenting that consist of spaces or tabs
<?php
$str = " This is a test
string spanning
multiple lines.
It contains three
sentences, each are
split on three lines.
The indentation decides
which lines belongs
to which sentence.";
$str = unindent($str);
echo '<pre>'.$str.'</pre>';
function unindent($snippet) {
// Add a line break to include the first line for space/tab removal.
$snippet = PHP_EOL . $snippet;
// Remove the preceding space of every line until any line runs out of it.
while (!preg_match('/' . PHP_EOL . '\S/', $snippet)) {
$snippet = preg_replace('/' . PHP_EOL . '[ \t]/', PHP_EOL, $snippet);
}
// Remove the added preceding line break and any trailing whitespace.
return trim($snippet);
}
?>
@lolandese
Copy link
Author

lolandese commented Sep 11, 2019

It consists of a loop that removes the first space of each line until any line does not start with a space or tab anymore.

Input

      This is a test                    
        string spanning 
        multiple lines.
      It contains three 
        sentences, each are 
        split on three lines.
      The indentation decides 
        which lines belongs 
        to which sentence.

Output

This is a test                    
  string spanning 
  multiple lines.
It contains three 
  sentences, each are 
  split on three lines.
The indentation decides 
  which lines belongs 
  to which sentence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment