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 | 8 | public static function detect($string) |
|
25 | { |
||
26 | // EUC-CN 是 GB2312 的表现方式 |
||
27 | 8 | $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 | 8 | return $charset; |
|
30 | } |
||
31 | |||
32 | /** |
||
33 | * 将任意编码的字符串转成 UTF-8. |
||
34 | * |
||
35 | * @param string $string |
||
36 | * @param string|null $fromCharset 强制指定编码 |
||
37 | * |
||
38 | * @return string 转码后的字符串 |
||
39 | 2 | */ |
|
40 | public static function toUtf($string, $fromCharset = null) |
||
41 | 2 | { |
|
42 | return self::convertTo($string, 'UTF-8', $fromCharset); |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * 将任意编码的字符串转成中文编码. |
||
47 | * |
||
48 | * @param string $string |
||
49 | * @param string|null $fromCharset 强制指定编码 |
||
50 | * |
||
51 | 1 | * @return string 转码后的字符串 |
|
52 | */ |
||
53 | 1 | public static function toCn($string, $fromCharset = null) |
|
54 | { |
||
55 | return self::convertTo($string, 'EUC-CN', $fromCharset); |
||
56 | } |
||
57 | |||
58 | /** |
||
59 | * 判断字符串是否是 UTF-8 编码 |
||
60 | * |
||
61 | * @param string $string 待检测的字符串 |
||
62 | * |
||
63 | 1 | * @return boolean |
|
64 | */ |
||
65 | 1 | public static function isUtf8($string) |
|
66 | { |
||
67 | return 'UTF-8' === self::detect($string); |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * 转换编码 |
||
72 | * |
||
73 | * @param string $string 待转换的字符串 |
||
74 | * @param string $targetCharset 目标编码 |
||
75 | * @param string|null $fromCharset 强制指定编码 |
||
76 | 6 | * |
|
77 | * @return string |
||
78 | 6 | */ |
|
79 | 6 | public static function convertTo($string, $targetCharset, $fromCharset = null) |
|
80 | { |
||
81 | $charset = null === $fromCharset ? self::detect($string): $fromCharset; |
||
82 | $converted = @iconv($charset, $targetCharset . '//TRANSLIT//IGNORE', $string); |
||
83 | // if (false === $converted) { |
||
84 | 6 | // $converted = mb_convert_encoding($string, $targetCharset); |
|
85 | // } |
||
86 | |||
87 | return $converted; |
||
0 ignored issues
–
show
|
|||
88 | } |
||
89 | } |
If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.