Remove non-utf8 characters from string

后端 未结 18 1421
心在旅途
心在旅途 2020-11-22 11:56

Im having a problem with removing non-utf8 characters from string, which are not displaying properly. Characters are like this 0x97 0x61 0x6C 0x6F (hex representation)

相关标签:
18条回答
  • 2020-11-22 12:30

    This function removes all NON ASCII characters, it's useful but not solving the question:
    This is my function that always works, regardless of encoding:

    function remove_bs($Str) {  
      $StrArr = str_split($Str); $NewStr = '';
      foreach ($StrArr as $Char) {    
        $CharNo = ord($Char);
        if ($CharNo == 163) { $NewStr .= $Char; continue; } // keep £ 
        if ($CharNo > 31 && $CharNo < 127) {
          $NewStr .= $Char;    
        }
      }  
      return $NewStr;
    }
    

    How it works:

    echo remove_bs('Hello õhowå åare youÆ?'); // Hello how are you?
    
    0 讨论(0)
  • 2020-11-22 12:31

    I have made a function that deletes invalid UTF-8 characters from a string. I'm using it to clear description of 27000 products before it generates the XML export file.

    public function stripInvalidXml($value) {
        $ret = "";
        $current;
        if (empty($value)) {
            return $ret;
        }
        $length = strlen($value);
        for ($i=0; $i < $length; $i++) {
            $current = ord($value{$i});
            if (($current == 0x9) || ($current == 0xA) || ($current == 0xD) || (($current >= 0x20) && ($current <= 0xD7FF)) || (($current >= 0xE000) && ($current <= 0xFFFD)) || (($current >= 0x10000) && ($current <= 0x10FFFF))) {
                    $ret .= chr($current);
            }
            else {
                $ret .= "";
            }
        }
        return $ret;
    }
    
    0 讨论(0)
  • 2020-11-22 12:31

    So the rules are that the first UTF-8 octlet has the high bit set as a marker, and then 1 to 4 bits to indicate how many additional octlets; then each of the additional octlets must have the high two bits set to 10.

    The pseudo-python would be:

    newstring = ''
    cont = 0
    for each ch in string:
      if cont:
        if (ch >> 6) != 2: # high 2 bits are 10
          # do whatever, e.g. skip it, or skip whole point, or?
        else:
          # acceptable continuation of multi-octlet char
          newstring += ch
        cont -= 1
      else:
        if (ch >> 7): # high bit set?
          c = (ch << 1) # strip the high bit marker
          while (c & 1): # while the high bit indicates another octlet
            c <<= 1
            cont += 1
            if cont > 4:
               # more than 4 octels not allowed; cope with error
          if !cont:
            # illegal, do something sensible
          newstring += ch # or whatever
    if cont:
      # last utf-8 was not terminated, cope
    

    This same logic should be translatable to php. However, its not clear what kind of stripping is to be done once you get a malformed character.

    0 讨论(0)
  • 2020-11-22 12:32

    Using a regex approach:

    $regex = <<<'END'
    /
      (
        (?: [\x00-\x7F]                 # single-byte sequences   0xxxxxxx
        |   [\xC0-\xDF][\x80-\xBF]      # double-byte sequences   110xxxxx 10xxxxxx
        |   [\xE0-\xEF][\x80-\xBF]{2}   # triple-byte sequences   1110xxxx 10xxxxxx * 2
        |   [\xF0-\xF7][\x80-\xBF]{3}   # quadruple-byte sequence 11110xxx 10xxxxxx * 3 
        ){1,100}                        # ...one or more times
      )
    | .                                 # anything else
    /x
    END;
    preg_replace($regex, '$1', $text);
    

    It searches for UTF-8 sequences, and captures those into group 1. It also matches single bytes that could not be identified as part of a UTF-8 sequence, but does not capture those. Replacement is whatever was captured into group 1. This effectively removes all invalid bytes.

    It is possible to repair the string, by encoding the invalid bytes as UTF-8 characters. But if the errors are random, this could leave some strange symbols.

    $regex = <<<'END'
    /
      (
        (?: [\x00-\x7F]               # single-byte sequences   0xxxxxxx
        |   [\xC0-\xDF][\x80-\xBF]    # double-byte sequences   110xxxxx 10xxxxxx
        |   [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences   1110xxxx 10xxxxxx * 2
        |   [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3 
        ){1,100}                      # ...one or more times
      )
    | ( [\x80-\xBF] )                 # invalid byte in range 10000000 - 10111111
    | ( [\xC0-\xFF] )                 # invalid byte in range 11000000 - 11111111
    /x
    END;
    function utf8replacer($captures) {
      if ($captures[1] != "") {
        // Valid byte sequence. Return unmodified.
        return $captures[1];
      }
      elseif ($captures[2] != "") {
        // Invalid byte of the form 10xxxxxx.
        // Encode as 11000010 10xxxxxx.
        return "\xC2".$captures[2];
      }
      else {
        // Invalid byte of the form 11xxxxxx.
        // Encode as 11000011 10xxxxxx.
        return "\xC3".chr(ord($captures[3])-64);
      }
    }
    preg_replace_callback($regex, "utf8replacer", $text);
    

    EDIT:

    • !empty(x) will match non-empty values ("0" is considered empty).
    • x != "" will match non-empty values, including "0".
    • x !== "" will match anything except "".

    x != "" seem the best one to use in this case.

    I have also sped up the match a little. Instead of matching each character separately, it matches sequences of valid UTF-8 characters.

    0 讨论(0)
  • 2020-11-22 12:34

    How about iconv:

    http://php.net/manual/en/function.iconv.php

    Haven't used it inside PHP itself but its always performed well for me on the command line. You can get it to substitute invalid characters.

    0 讨论(0)
  • 2020-11-22 12:36

    You can use mbstring:

    $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
    

    ...will remove invalid characters.

    See: Replacing invalid UTF-8 characters by question marks, mbstring.substitute_character seems ignored

    0 讨论(0)
提交回复
热议问题