当前位置: 首页 > 工具软件 > iOS Emoji > 使用案例 >

iOS emoji过滤(实际为站位4字符的问题)

齐威
2023-12-01

意外发现微信获取的用户名 带有emoji 然后与后台交互就出问题了

emoji的问题就是字符编码超过了4位 导致后台数据库不支持 后台试了下来说出问题的地方太多不能改 就只好前端过滤emoji了

百度一堆没用 VPN出问题了 没能google 只好自己写了

因为是四位编码出问题所以 就写了如下 把四位编码的字符改为""的方法

#pragma mark - 过滤四位以上字符
+ (NSString *)filterMoreThanFourString:(NSString *)string {
    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *newStr = @"";
    for(int i =0; i < [string length]; ){
        NSString *temp = nil;
        for (int j = 1; j <= string.length - i; j++) {
            temp = [string substringWithRange:NSMakeRange(i,j)];
            temp = [temp stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            if (temp) {
                i += j;
//                NSLog(@"占%d位的字符:%@",j,temp);
                break;
            }
        }
//        NSLog(@"到%d位最后的字是:%@",i,temp);
        if ([temp lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 3) {
            temp = @"";
        }
        newStr = [NSString stringWithFormat:@"%@%@",newStr,temp];
    }
    return newStr;
}
稍微改动成 多位字符替换的成指定字符的方法:

#pragma mark  过滤max位以上字符(不包括max
+ (NSString *)filterMoreThanNumber:(NSInteger)maxNum String:(NSString *)string replaceString:(NSString *)replaceString UsingEncoding:(NSStringEncoding)usingEncoding{
    string = [string stringByAddingPercentEscapesUsingEncoding:usingEncoding];
    NSString *newStr = @"";
    for(int i =0; i < [string length]; ){
        NSString *temp = nil;
        for (int j = 1; j <= string.length - i; j++) {
            temp = [string substringWithRange:NSMakeRange(i,j)];
            temp = [temp stringByReplacingPercentEscapesUsingEncoding:usingEncoding];
            if (temp) {
                i += j;
//                NSLog(@"占%d位的字符:%@",j,temp);
                break;
            }
        }
//        NSLog(@"到%d位最后的字是:%@",i,temp);
        if ([temp lengthOfBytesUsingEncoding:usingEncoding] > maxNum) {
            temp = replaceString;
        }
        newStr = [NSString stringWithFormat:@"%@%@",newStr,temp];
    }
    return newStr;
}


 类似资料: