Conversion and Judgment of String Encoding for PHP Learning Notes
- 2021-06-28 09:00:37
- OfStack
iconv('GBK', 'UTF-8//IGNORE', ' Script Home '); // Puts a string from GBK Encoding to UTF-8 Code
However, iconv only solves cases where the encoding is known beforehand. If the string encoding is unknown, it needs to be probed first, and mb_may be usedstring Extension Library:
mb_detect_encoding(' Script Home ');
But mb_detect_encoding had a hard injury and often had inaccurate judgement.Perhaps this will solve the problem:
// Use iconv Converting and determining equivalence is inefficient
function is_utf8 ($str) {
if ($str === iconv('UTF-8', 'UTF-8//IGNORE', $str)) {
return 'UTF-8';
}
}
// Multiple encoding scenarios
function detect_encoding ($str) {
foreach (array('GBK', 'UTF-8') as $v) {
if ($str === iconv($v, $v . '//IGNORE', $str)) {
return $v;
}
}
}
Once you get the string encoding information in the above way, you can use iconv or mb_convert_encoding to convert the encoding.