1
|
|
|
<?php
|
2
|
|
|
|
3
|
|
|
namespace Lagdo\DbAdmin\Driver\Utils;
|
4
|
|
|
|
5
|
|
|
use function str_replace;
|
6
|
|
|
use function preg_replace;
|
7
|
|
|
use function preg_match;
|
8
|
|
|
use function htmlspecialchars;
|
9
|
|
|
|
10
|
|
|
class Str
|
11
|
|
|
{
|
12
|
|
|
/**
|
13
|
|
|
* @inheritDoc
|
14
|
|
|
*/
|
15
|
|
|
public function html($string): string
|
16
|
|
|
{
|
17
|
|
|
if(!$string) {
|
18
|
|
|
return '';
|
19
|
|
|
}
|
20
|
|
|
$string = str_replace("\n", '<br>', $string);
|
21
|
|
|
return str_replace("\0", '�', htmlspecialchars($string, ENT_QUOTES, 'utf-8'));
|
22
|
|
|
}
|
23
|
|
|
|
24
|
|
|
/**
|
25
|
|
|
* @inheritDoc
|
26
|
|
|
*/
|
27
|
|
|
public function number(string $value): string
|
28
|
|
|
{
|
29
|
|
|
return preg_replace('~[^0-9]+~', '', $value);
|
30
|
|
|
}
|
31
|
|
|
|
32
|
|
|
/**
|
33
|
|
|
* @inheritDoc
|
34
|
|
|
*/
|
35
|
|
|
public function isUtf8(string $value): bool
|
36
|
|
|
{
|
37
|
|
|
// don't print control chars except \t\r\n
|
38
|
|
|
return (preg_match('~~u', $value) && !preg_match('~[\0-\x8\xB\xC\xE-\x1F]~', $value));
|
39
|
|
|
}
|
40
|
|
|
|
41
|
|
|
/**
|
42
|
|
|
* Create repeat pattern for preg
|
43
|
|
|
*
|
44
|
|
|
* @param string $pattern
|
45
|
|
|
* @param int $length
|
46
|
|
|
*
|
47
|
|
|
* @return string
|
48
|
|
|
*/
|
49
|
|
|
private function repeatPattern(string $pattern, int $length): string
|
50
|
|
|
{
|
51
|
|
|
// fix for Compilation failed: number too big in {} quantifier
|
52
|
|
|
// can create {0,0} which is OK
|
53
|
|
|
return str_repeat("$pattern{0,65535}", $length / 65535) . "$pattern{0," . ($length % 65535) . '}';
|
54
|
|
|
}
|
55
|
|
|
|
56
|
|
|
/**
|
57
|
|
|
* Shorten UTF-8 string
|
58
|
|
|
*
|
59
|
|
|
* @param string $string
|
60
|
|
|
* @param int $length
|
61
|
|
|
* @param string $suffix
|
62
|
|
|
*
|
63
|
|
|
* @return string
|
64
|
|
|
*/
|
65
|
|
|
public function shortenUtf8(string $string, int $length = 80, string $suffix = ''): string
|
66
|
|
|
{
|
67
|
|
|
if (!preg_match('(^(' . $this->repeatPattern("[\t\r\n -\x{10FFFF}]", $length) . ')($)?)u', $string, $match)) {
|
68
|
|
|
// ~s causes trash in $match[2] under some PHP versions, (.|\n) is slow
|
69
|
|
|
preg_match('(^(' . $this->repeatPattern("[\t\r\n -~]", $length) . ')($)?)', $string, $match);
|
70
|
|
|
}
|
71
|
|
|
return $this->html($match[1]) . $suffix . (isset($match[2]) ? '' : '<i>…</i>');
|
72
|
|
|
}
|
73
|
|
|
}
|
74
|
|
|
|