We're seeing encoding errors running this library in production.

Attempt to encode strings as valid UTF-8 before we do the gsub
replacement into the string, as this just breaks if passed invalid
UTF-8.