This looks really ugly, why not preg_replace_callback?