1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class Html |
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
|
|
|
* Html 相关 |
14
|
|
|
*/ |
15
|
|
|
class Html |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* htmlspecialchars 简化版 |
19
|
|
|
* |
20
|
|
|
* @see http://php.net/manual/zh/function.htmlspecialchars.php |
21
|
|
|
* |
22
|
|
|
* @param string $content HTML 内容 |
23
|
|
|
* @param boolean $doubleEncode 是否重复转化 |
24
|
|
|
* @param string $encoding 编码,默认 UTF-8 |
25
|
|
|
* |
26
|
|
|
* @return string |
27
|
|
|
*/ |
28
|
1 |
|
public static function encode($content, $doubleEncode = true, $encoding = 'UTF-8') |
29
|
|
|
{ |
30
|
1 |
|
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, $doubleEncode); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* htmlspecialchars_decode 简化版 |
35
|
|
|
* |
36
|
|
|
* @see http://php.net/manual/zh/function.htmlspecialchars-decode.php |
37
|
|
|
* |
38
|
|
|
* @param string $content HTML 内容 |
39
|
|
|
* |
40
|
|
|
* @return string |
41
|
|
|
*/ |
42
|
1 |
|
public static function decode($content) |
43
|
|
|
{ |
44
|
1 |
|
return htmlspecialchars_decode($content, ENT_QUOTES); |
45
|
|
|
} |
46
|
|
|
/** |
47
|
|
|
* strip_tags 从字符串中去除 HTML 和 PHP 标记 |
48
|
|
|
* 改良:不合法/错误的 html 标签也能匹配 |
49
|
|
|
* |
50
|
|
|
* @see http://php.net/manual/zh/function.strip-tags.php |
51
|
|
|
* |
52
|
|
|
* @param string $html |
53
|
|
|
* @param array $allowTags 区别于 strip_tags,例如 a 和 h1 标签,strip_tags 的需要写成'<a><h1>'这里就写 ['a', 'h1'] |
54
|
|
|
* |
55
|
|
|
* @return string |
56
|
|
|
*/ |
57
|
1 |
|
public static function stripTags($html, $allowTags = []) |
58
|
|
|
{ |
59
|
1 |
|
$allowTags = array_map('strtolower', $allowTags); |
60
|
|
|
return preg_replace_callback('/<\/?([^>\s]+)[^>]*>/i', function ($matches) use (&$allowTags) { |
61
|
1 |
|
return in_array(strtolower($matches[1]), $allowTags) ? $matches[0] : ''; |
62
|
1 |
|
}, $html); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|