如何删除字符串中的任何 utf8mb4 字符

How to remove any utf8mb4 characters in string

使用 C# 如何从字符串中删除 utf8mb4 字符(表情符号等),以便结果完全符合 utf8。

大多数解决方案都涉及更改数据库配置,但不幸的是我没有这种可能性。

这应该用 replacementCharacter 替换代理字符(甚至可以是 string.Empty

鉴于 utf8mb4,这是一个 MySql 问题。 Here there is the difference between utf8 and utf8mb4 in MySql. The difference is that utf8 doesn't support 4 byte utf8 sequences. By looking at the wiki,4 字节 utf8 序列是那些 > 0xFFFF,因此在 utf16 中需要两个 char(被命名为代理对)。此方法删除代理对字符。当找到 "coupled"(高 + 低代理对)时,将替换单个 replacementCharacter,否则将用 replacementCharacte 替换孤儿(错误的)高或低代理对。

public static string RemoveSurrogatePairs(string str, string replacementCharacter = "?")
{
    if (str == null)
    {
        return null;
    }

    StringBuilder sb = null;

    for (int i = 0; i < str.Length; i++)
    {
        char ch = str[i];

        if (char.IsSurrogate(ch))
        {
            if (sb == null)
            {
                sb = new StringBuilder(str, 0, i, str.Length);
            }

            sb.Append(replacementCharacter);

            // If there is a high+low surrogate, skip the low surrogate
            if (i + 1 < str.Length && char.IsHighSurrogate(ch) && char.IsLowSurrogate(str[i + 1]))
            {
                i++;
            }
        }
        else if (sb != null)
        {
            sb.Append(ch);
        }
    }

    return sb == null ? str : sb.ToString();
}