1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class Charset |
4
|
|
|
* |
5
|
|
|
* @link https://www.icy2003.com/ |
6
|
|
|
* @author icy2003 <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2017, icy2003 |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace icy2003\php\ihelpers; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* 编码转换 |
14
|
|
|
*/ |
15
|
|
|
class Charset |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* 检测字符串的编码格式. |
19
|
|
|
* |
20
|
|
|
* @param string $string |
21
|
|
|
* |
22
|
|
|
* @return string 编码 |
23
|
|
|
*/ |
24
|
5 |
|
public static function detect($string) |
25
|
|
|
{ |
26
|
|
|
// EUC-CN 是 GB2312 的表现方式 |
27
|
5 |
|
$charset = mb_detect_encoding($string, 'UTF-8,EUC-CN,ISO-8859-2,ASCII,UTF-7,EUC-JP,SJIS,eucJP-win,SJIS-win,JIS,ISO-2022-JP', true); |
28
|
|
|
|
29
|
5 |
|
return $charset; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* 将任意编码的字符串转成 UTF-8. |
34
|
|
|
* |
35
|
|
|
* @param string $string |
36
|
|
|
* |
37
|
|
|
* @return string 转码后的字符串 |
38
|
|
|
*/ |
39
|
1 |
|
public static function toUtf($string) |
40
|
|
|
{ |
41
|
1 |
|
return self::convertTo($string, 'UTF-8'); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* 将任意编码的字符串转成中文编码. |
46
|
|
|
* |
47
|
|
|
* @param string $string |
48
|
|
|
* |
49
|
|
|
* @return string 转码后的字符串 |
50
|
|
|
*/ |
51
|
1 |
|
public static function toCn($string) |
52
|
|
|
{ |
53
|
1 |
|
return self::convertTo($string, 'EUC-CN'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* 判断字符串是否是 UTF-8 编码 |
58
|
|
|
* |
59
|
|
|
* @param string $string 待检测的字符串 |
60
|
|
|
* |
61
|
|
|
* @return boolean |
62
|
|
|
*/ |
63
|
1 |
|
public static function isUtf8($string) |
64
|
|
|
{ |
65
|
1 |
|
return 'UTF-8' === self::detect($string); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* 转换编码 |
70
|
|
|
* |
71
|
|
|
* @param string $string 待转换的字符串 |
72
|
|
|
* @param string $targetCharset 目标编码 |
73
|
|
|
* |
74
|
|
|
* @return string |
75
|
|
|
*/ |
76
|
3 |
|
public static function convertTo($string, $targetCharset) |
77
|
|
|
{ |
78
|
3 |
|
$charset = self::detect($string); |
79
|
3 |
|
$converted = @iconv($charset, $targetCharset . '//TRANSLIT//IGNORE', $string); |
80
|
|
|
// if (false === $converted) { |
81
|
|
|
// $converted = mb_convert_encoding($string, $targetCharset); |
82
|
|
|
// } |
83
|
|
|
|
84
|
3 |
|
return $converted; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|