不適切な形式のバイト シーケンスを処理する関数を定義し、文字列を htmlentties に渡す前に関数を呼び出します。関数の定義にはさまざまな方法があります。
Windows を使用していない場合は、最初に UConverter::transcode を試してください。
http://pecl.php.net/package/intl
バイトを直接処理する場合は、以前の回答を参照してください。
https://stackoverflow.com/a/13695364/531320
最後のオプションは、PHP 拡張機能を開発することです。php_next_utf8_char のおかげで難しくありません。これがコードサンプルです。「スクラブ」という名前は Ruby 2.1 に由来します ( Equivalent of Iconv.conv("UTF-8//IGNORE",...) in Ruby 1.9.X? を参照) 。
// header file
// PHP_FUNCTION(utf8_scrub);
#include "ext/standard/html.h"
#include "ext/standard/php_smart_str.h"
const zend_function_entry utf8_string_functions[] = {
PHP_FE(utf8_scrub, NULL)
PHP_FE_END
};
PHP_FUNCTION(utf8_scrub)
{
char *str = NULL;
int len, status;
size_t pos = 0, old_pos;
unsigned int code_point;
smart_str buf = {0};
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &len) == FAILURE) {
return;
}
while (pos < len) {
old_pos = pos;
code_point = php_next_utf8_char((const unsigned char *) str, len, &pos, &status);
if (status == FAILURE) {
smart_str_appendl(&buf, "\xEF\xBF\xBD", 3);
} else {
smart_str_appendl(&buf, str + old_pos, pos - old_pos);
}
}
smart_str_0(&buf);
RETURN_STRINGL(buf.c, buf.len, 0);
smart_str_free(&buf);
}