1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Xparse\Parser\Helper; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Try to convert input encoding |
9
|
|
|
* |
10
|
|
|
* @author Ivan Shcherbak <[email protected]> |
11
|
|
|
*/ |
12
|
|
|
class ToUtfConverter implements EncodingConverterInterface |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var null|string[] |
17
|
|
|
*/ |
18
|
|
|
private $supportedEncodings; |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
public function convert(string $html, string $contentType = ''): string |
22
|
|
|
{ |
23
|
|
|
$encoding = ''; |
24
|
|
|
if (preg_match('!^.*charset=([A-Za-z0-9-]{4,})$!', $contentType, $contentTypeData) === 1) { |
25
|
|
|
$encoding = $contentTypeData[1]; |
26
|
|
|
} elseif (preg_match("!.*<meta.*charset=[\"']?[ \t]*([A-Za-z0-9-]{4,})[ \t]*[\"']!mi", $html, $metaContentType) === 1) { |
27
|
|
|
$encoding = $metaContentType[1]; |
28
|
|
|
} |
29
|
|
|
$encoding = strtolower($encoding); |
30
|
|
|
if ($encoding !== '' && in_array($encoding, $this->getSupportedEncodings(), true)) { |
31
|
|
|
$html = mb_convert_encoding($html, 'utf-8', $encoding); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return $html; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
*/ |
40
|
|
|
private function getSupportedEncodings(): array |
41
|
|
|
{ |
42
|
|
|
if ($this->supportedEncodings === null) { |
43
|
|
|
$this->supportedEncodings = []; |
44
|
|
|
$findAliases = function_exists('mb_encoding_aliases'); |
45
|
|
|
foreach (mb_list_encodings() as $encoding) { |
46
|
|
|
$encoding = strtolower($encoding); |
47
|
|
|
if ($encoding !== 'utf-8' && $encoding !== 'utf8') { |
48
|
|
|
$this->supportedEncodings[] = $encoding; |
49
|
|
|
if ($findAliases) { |
50
|
|
|
foreach (mb_encoding_aliases($encoding) as $encodingAlias) { |
51
|
|
|
$encodingAlias = strtolower($encodingAlias); |
52
|
|
|
$this->supportedEncodings[] = $encodingAlias; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
return $this->supportedEncodings; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
} |