Shouldn't the condition be reversed here ?
The part you moved above was in else, yet it's still using the same condition to do the substr operation.
Please double check.