Could `preg_replace` do all this work for you?