Skip to content

Instantly share code, notes, and snippets.

@rvanvelzen
Created February 10, 2012 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rvanvelzen/1790237 to your computer and use it in GitHub Desktop.
Save rvanvelzen/1790237 to your computer and use it in GitHub Desktop.
PHP unindent
<?php
/**
* Unindent a given string
*
* Empty lines are skipped.
*
* N.b.: de longest common substring is used, as a result all the
* indenting has to be exactly the same. Proper unindenting may fail
* otherwise.
*
* @param string $text
* @return string
*/
function unindent($text) {
if (preg_match('{\A[\r\n]*(\h+)[^\r\n]*+(?:[\r\n]++(?>\1[^\r\n]*+(?:[\r\n]+|\z)|[\r\n]+)+)?\z}', rtrim($text), $match)) {
$text = preg_replace('{^' . $match[1] . '}m', '', $text);
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment