Check the regex has a match before using it.

This works around an obvious bug in PHP that sometimes removes the text
entirely, even though there are no matches and that shouldn't be
possible.