Passed
Push — master ( a68137...f0b2de )
by ma
02:12
created

StringTool::autoCharset()   C

Complexity

Conditions 13
Paths 32

Size

Total Lines 26
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 20
c 0
b 0
f 0
nc 32
nop 3
dl 0
loc 26
rs 6.6166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace tinymeng\tools;
3
/**
4
 * Class 字符串类
5
 * @package tinymeng\tools
6
 * @Author: TinyMeng <[email protected]>
7
 * @Created: 2018/11/26
8
 */
9
class StringTool
10
{
11
    /**
12
     * Function Name: 手写字母大写
13
     * @param $str
14
     * @return string
15
     * @author Tinymeng <[email protected]>
16
     * @date: 2019/9/26 10:19
17
     */
18
    static public function uFirst($str):string{
19
        return ucfirst(strtolower($str));
20
    }
21
22
    /**
23
     * Name: 生成随机字符串
24
     * Author: Tinymeng <[email protected]>
25
     * @param int $length 字符串长度
26
     * @return string
27
     */
28
    public static function generateRandomString($length = 10):string {
29
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
30
        return substr(str_shuffle($characters), 0, $length);
31
    }
32
33
34
    /**
35
     * 获取唯一设备号
36
     * @Author: TinyMeng <[email protected]>
37
     * @param string $namespace
38
     * @return string
39
     */
40
    static public function createChannelId($namespace = ''):string {
41
        static $guid = '';
42
        $uid = uniqid("", true);
43
        $data = $namespace. md5(time() . mt_rand(1,1000000)).uniqid();
44
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
45
        $guid = substr($hash, 0, 8) .
46
            '-' .
47
            substr($hash, 8, 4) .
48
            '-' .
49
            substr($hash, 12, 4) .
50
            '-' .
51
            substr($hash, 16, 4) .
52
            '-' .
53
            substr($hash, 20, 12);
54
        return $guid;
55
    }
56
57
    /**
58
     * 获取md5中16位小写
59
     * 实现java的 MD516.Bit16
60
     * @Author: TinyMeng <[email protected]>
61
     * @param $str
62
     * @return string
63
     */
64
    static public function md5Bit16($str):string {
65
        return strtoupper(substr(md5($str),8,16));
66
    }
67
68
    /**
69
     * 获取时间戳(13位精确到豪妙)
70
     * @Author: TinyMeng <[email protected]>
71
     * @param null|int $time
72
     * @return int
73
     */
74
    static public function millisecond($time = null) :int{
75
        if(empty($time)){
76
            list($msec, $sec) = explode(' ', microtime());
77
            $millisecond = (int)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
78
        }elseif(is_numeric($time) && strlen((string)$time)==10){
79
            $millisecond = (string)$time."000";
80
        }else{
81
            $millisecond = strtotime($time)."000";
82
        }
83
        return (int)$millisecond;
84
    }
85
86
    /**
87
     * Name: 是否包含中文
88
     * Author: Tinymeng <[email protected]>
89
     * @param string $string
90
     * @return bool
91
     */
92
    public static function isContainChinese($string=''):bool {
93
        $result = preg_match('/[\x{4e00}-\x{9fa5}]/u', $string);
94
        return $result == 0 ? false : true;
95
    }
96
97
    /**
98
     * Name: 是否全是中文
99
     * Author: Tinymeng <[email protected]>
100
     * @param string $string
101
     * @return bool
102
     */
103
    public static function isAllChinese($string=''):bool {
104
        $result = preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $string);
105
        return $result == 0 ? false : true;
106
    }
107
108
    /**
109
     * 判断手机号码
110
     * Author : MYL <[email protected]>
111
     * Updater:
112
     * @param string $string
113
     * @return bool
114
     */
115
    public static function isMobile($string=''):bool {
116
        if (!preg_match("/(^1[3|4|5|7|8][0-9]{9}$)/", $string)) {
117
            return false;
118
        }
119
        return true;
120
    }
121
122
    /**
123
     * Description:  科学计数法转化正常数值输出
124
     * Author: JiaMeng <[email protected]>
125
     * Updater:
126
     * @param string $num 科学计数法字符串  如 2.1E-5
127
     * @param int $double   小数点保留位数 默认3位
128
     * @return string
129
     */
130
    public static function sctonum($num, $double = 3){
131
        if(false !== stripos($num, "e")){
132
            $a = explode("e",strtolower($num));
133
            return bcmul($a[0], bcpow(10, $a[1], $double), $double);
134
        }
135
        return $num;
136
    }
137
138
    /**
139
     * Name: 自动转换字符集 支持数组转换
140
     * Author: Tinymeng <[email protected]>
141
     * @param $string
142
     * @param string $from
143
     * @param string $to
144
     * @return array|false|string|string[]|null
145
     */
146
    public static function autoCharset($string, $from='gbk', $to='utf-8') {
147
        $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
148
        $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
149
        if (strtoupper($from) === strtoupper($to) || empty($string) || (is_scalar($string) && !is_string($string))) {
150
            //如果编码相同或者非字符串标量则不转换
151
            return $string;
152
        }
153
        if (is_string($string)) {
154
            if (function_exists('mb_convert_encoding')) {
155
                return mb_convert_encoding($string, $to, $from);
156
            } elseif (function_exists('iconv')) {
157
                return iconv($from, $to, $string);
158
            } else {
159
                return $string;
160
            }
161
        } elseif (is_array($string)) {
162
            foreach ($string as $key => $val) {
163
                $_key = self::autoCharset($key, $from, $to);
164
                $string[$_key] = self::autoCharset($val, $from, $to);
165
                if ($key != $_key)
166
                    unset($string[$key]);
167
            }
168
            return $string;
169
        }
170
        else {
171
            return $string;
172
        }
173
    }
174
175
    /**
176
     * Description:  过滤html里a标签
177
     * Author: song <[email protected]>
178
     * Updater:
179
     * @param $html
180
     * @return string
181
     */
182
    public static function filterATag($html=''):string {
183
        return preg_replace("#<a[^>]*>(.*?)</a>#is", "$1", $html);
184
    }
185
186
    /**
187
     * Description:  删除html里a标签及内容
188
     * Author: song <[email protected]>
189
     * Updater:
190
     * @param $html
191
     * @return string
192
     */
193
    public static function deleteATag($html=''):string {
194
        return preg_replace("#<a[^>]*>(.*?)</a>#is", "", $html);
195
    }
196
197
    /**
198
     * Description:  时间转换
199
     * Author: JiaMeng <[email protected]>
200
     * Updater:
201
     * @param string $date 时间
202
     * @param bool $is_timestamp   是否是时间戳
203
     * @return string
204
     */
205
    public static function getTime($date,$is_timestamp=false):string {
206
        if($is_timestamp === true){
207
            $time = $date;
208
        }else{
209
            $time = strtotime($date);//时间转换为时间戳
210
        }
211
212
        if($time >= time()){
213
            return '刚刚';
214
        }
215
        $seconds = time() - $time;
216
        if($seconds <= 60){
217
            return '刚刚';
218
        }
219
        $minutes = intval($seconds / 60);
220
        if($minutes <= 60){
221
            return $minutes.'分钟前';
222
        }
223
        $hours = intval($minutes / 60);
224
        if($hours <= 24){
225
            return $hours.'小时前';
226
        }
227
        $days = intval($hours / 24);
228
        if($days <= 3){
229
            return $days.'天前';
230
        }
231
        if($days <= 365){
232
            return date('m-d',/** @scrutinizer ignore-type */ $time);
233
        }
234
        return date('Y-m-d',$time);
0 ignored issues
show
Bug introduced by
It seems like $time can also be of type string; however, parameter $timestamp of date() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

234
        return date('Y-m-d',/** @scrutinizer ignore-type */ $time);
Loading history...
235
    }
236
237
    /**
238
     * Name: 压缩html代码
239
     * Author: Tinymeng <[email protected]>
240
     * @param string $html_source
241
     * @return string
242
     */
243
    static public function compressHtml($html_source):string {
244
        $chunks   = preg_split('/(<!--<nocompress>-->.*?<!--<\/nocompress>-->|<nocompress>.*?<\/nocompress>|<pre.*?\/pre>|<textarea.*?\/textarea>|<script.*?\/script>)/msi', $html_source, -1, PREG_SPLIT_DELIM_CAPTURE);
245
        $compress = '';
246
        foreach ($chunks as $c) {
247
            if (strtolower(substr($c, 0, 19)) == '<!--<nocompress>-->') {
248
                $c        = substr($c, 19, strlen($c) - 19 - 20);
249
                $compress .= $c;
250
                continue;
251
            } elseif (strtolower(substr($c, 0, 12)) == '<nocompress>') {
252
                $c        = substr($c, 12, strlen($c) - 12 - 13);
253
                $compress .= $c;
254
                continue;
255
            } elseif (strtolower(substr($c, 0, 4)) == '<pre' || strtolower(substr($c, 0, 9)) == '<textarea') {
256
                $compress .= $c;
257
                continue;
258
            } elseif (strtolower(substr($c, 0, 7)) == '<script' && strpos($c, '//') != false && (strpos($c, "\r") !== false || strpos($c, "\n") !== false)) { // JS代码,包含“//”注释的,单行代码不处理
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strpos($c, '//') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
259
                $tmps = preg_split('/(\r|\n)/ms', $c, -1, PREG_SPLIT_NO_EMPTY);
260
                $c    = '';
261
                foreach ($tmps as $tmp) {
262
                    if (strpos($tmp, '//') !== false) { // 对含有“//”的行做处理
263
                        if (substr(trim($tmp), 0, 2) == '//') { // 开头是“//”的就是注释
264
                            continue;
265
                        }
266
                        $chars   = preg_split('//', $tmp, -1, PREG_SPLIT_NO_EMPTY);
267
                        $is_quot = $is_apos = false;
268
                        foreach ($chars as $key => $char) {
269
                            if ($char == '"' && !$is_apos && $key > 0 && $chars[$key - 1] != '\\') {
270
                                $is_quot = !$is_quot;
0 ignored issues
show
introduced by
The condition $is_quot is always false.
Loading history...
271
                            } elseif ($char == '\'' && !$is_quot && $key > 0 && $chars[$key - 1] != '\\') {
272
                                $is_apos = !$is_apos;
273
                            } elseif ($char == '/' && $chars[$key + 1] == '/' && !$is_quot && !$is_apos) {
274
                                $tmp = substr($tmp, 0, $key); // 不是字符串内的就是注释
275
                                break;
276
                            }
277
                        }
278
                    }
279
                    $c .= $tmp;
280
                }
281
            }
282
            $c = preg_replace('/[\\n\\r\\t]+/', ' ', $c); // 清除换行符,清除制表符
283
            $c = preg_replace('/\\s{2,}/', ' ', $c); // 清除额外的空格
284
            $c = preg_replace('/>\\s</', '> <', $c); // 清除标签间的空格
285
            $c = preg_replace('/\\/\\*.*?\\*\\//i', '', $c); // 清除 CSS & JS 的注释
286
            $c = preg_replace('/<!--[^!]*-->/', '', $c); // 清除 HTML 的注释
287
            $compress .= $c;
288
        }
289
        return $compress;
290
    }
291
292
    /**
293
     * Description:  html标签替换成特定小程序标签
294
     * Author: JiaMeng <[email protected]>
295
     * Updater:
296
     * @param string $content
297
     * @return mixed
298
     */
299
    static public function htmlReplaceXcx(string $content):string {
300
        $content = str_replace("\r\n","",$content);//出除回车和换行符
301
        $content = preg_replace("/style=\".*?\"/si",'',$content);//style样式
302
        $content = preg_replace(["/<strong.*?>/si", "/<\/strong>/si"],['<text class="wx-strong">','</text>'],$content);//strong
303
        $content = preg_replace(["/<p.*?>/si", "/<\/p>/si"],['<view class="wx-p">','</view>'],$content);//p
304
        $content = preg_replace(["/<a.*?>/si", "/<\/a>/si"],['<text class="wx-a">','</text>'],$content);//a
305
        $content = preg_replace(["/<span.*?>/si", "/<\/span>/si"],['<text class="wx-span">','</text>'],$content);//span
306
        $content = preg_replace(["/<h[1-6].*?>/si", "/<\/h[1-6]>/si"],['<view class="wx-h">','</view>'],$content);//h
307
        $content = preg_replace("/<img.*?/si",'<image class="wx-img"',$content);//img
308
        return $content;
309
    }
310
311
    /**
312
     * Description:  html P标签替换成特定Span标签(安卓app使用)
313
     * Author: JiaMeng <[email protected]>
314
     * Updater:
315
     * @param string $content
316
     * @return string
317
     */
318
    static public function pReplaceSpan(string $content):string {
319
        $content = str_replace(["\r","\n","\t"],'',$content);
320
        $content = preg_replace(["/<p/si", "/<\/p>/si"],['<span','</span><br>'],$content);//p
321
        return $content;
322
    }
323
324
    /**
325
     * Description:  过滤标点符号
326
     * @author: JiaMeng <[email protected]>
327
     * Updater:
328
     * @param  string $keyword
329
     * @return string
330
     */
331
    static public function filterPunctuation($keyword){
332
        $keyword = str_replace(["\r\n", "\r", "\n"," "," "], "", trim($keyword));//删除空格
333
        $keyword = preg_replace('# #','',$keyword);
334
        $keyword = preg_replace("/[ '.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",'',$keyword);
335
        return $keyword;
336
    }
337
338
    /**
339
     * Description:  过滤html标签
340
     * @author: JiaMeng <[email protected]>
341
     * Updater:
342
     * @param $content
343
     * @param string $allowable_tags
344
     * @return string
345
     */
346
    static public function stripTags($content,$allowable_tags = '<font>'){
347
        $content = strip_tags($content,$allowable_tags);//替换标签
348
        $content = str_replace(["\r\n", "\r", "\n"," "], "", trim($content));//删除空格
349
        return $content;
350
    }
351
352
}