Search and replace - spaces before and after control structures
February 5, 2014
Again struggling to bring my code up to PSR2 coding standards I've run into another little typing glitch PHP Code Sniffer Fixer will not fix: there should be one white spaces before and after control structures.
So this code
if($a === $b) {
bar();
}elseif($a > $b) {
$foo->bar($arg1);
}else{
BazClass::bar($arg2, $arg3);
should be
if ($a === $b) {
bar();
} elseif ($a > $b) {
$foo->bar($arg1);
} else {
BazClass::bar($arg2, $arg3);
I'm looking for this string
[^\S\n]*(if|else|elseif|else if|while|do-while|for|foreach|switch|declare|return|include|require|require_once|include_once)[^\S\n]*
and will replace with
$1
Double negation
I came across this tip on stackoverflow and it really shines in picking up spaces but not newlines chars:
[^\S\n]
That is, not-not-whitespace or not-newline. Distributing the outer not (i.e., the complementing ^ in the character class) with De Morgan's law, this is equivalent to “whitespace and not newline,”
And tabs? Those should not be there according to PSR2 standards, 4 spaces should be used instead.