Last active
June 11, 2022 20:27
-
-
Save elifiner/91c6578ad70a713e90f0bfc288c7b125 to your computer and use it in GitHub Desktop.
Indent and de-indent multiline strings in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function dedent($str) | |
{ | |
$parts = array_filter(explode("\n", $str), function($part) { | |
return trim($part); | |
}); | |
$spaces = min(array_map(function($part) { | |
preg_match('#^ *#', $part, $matches); | |
return strlen($matches[0]); | |
}, $parts)); | |
$parts = array_map(function($part) use ($spaces) { | |
return substr($part, $spaces); | |
}, $parts); | |
return implode("\n", $parts); | |
} | |
function indent($str, $spaces) { | |
$parts = array_filter(explode("\n", $str)); | |
$parts = array_map(function ($part) use ($spaces) { | |
return str_repeat(' ', $spaces).$part; | |
}, $parts); | |
return implode("\n", $parts); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@michaeljoseph Sure should, thanks!