UTF-8 validation in PHP without using preg_match()

后端 未结 5 658
梦如初夏
梦如初夏 2021-01-01 01:43

I need to validate some user input that is encoded in UTF-8. Many have recommended using the following code:

preg_match(\'/\\A(
     [\\x09\\x0A\\x0D\\x20-\\         


        
5条回答
  •  生来不讨喜
    2021-01-01 02:13

    Here is a string-function based solution:

    http://www.php.net/manual/en/function.mb-detect-encoding.php#85294

     128){
                if(($c >= 254)) return false;
                elseif($c >= 252) $bits=6;
                elseif($c >= 248) $bits=5;
                elseif($c >= 240) $bits=4;
                elseif($c >= 224) $bits=3;
                elseif($c >= 192) $bits=2;
                else return false;
                if(($i+$bits) > $len) return false;
                while($bits > 1){
                    $i++;
                    $b=ord($str[$i]);
                    if($b < 128 || $b > 191) return false;
                    $bits--;
                }
            }
        }
        return true;
    }
    ?>
    

提交回复
热议问题