preg_replace PREG_BAD_UTF8_ERROR

2019-07-13 11:58发布

问题:

i have an annoying problem with preg_replace and charsets. I'm doing a couple preg_replace in a row but unfortunate the first time any special character like äöüß is inserted by preg_replace i'm getting PREG_BAD_UTF8_ERROR on subsequent calls.

Beside that the special characters inserted are displayed just fine, they just break any subsequent preg_replace call. Is preg_ utf-8 only?

The text preg_replace is working on is coming from MySQL Database, also the replacement is crafted in the php file with values from MySQL. mb_detect_encoding() says ASCII for the text until the first replacement with special characters, it then detects UTF-8, so it changes and this might be the problem.

For your information i'm working with iso-8859-1 encoding (PHP, MySQL, meta-charset). Furthermore i have a workaround with htmlentities on the replacement string that is working for now.

Any ideas on how to solve it?

回答1:

What you are looking for is probably mb_ereg_replace. It handles multibyte encodings and should perform fine with differrent ones. Be sure to use mb_regex_encoding along with it.