1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace BrowscapPHP\Helper; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* class to help quoting strings for using a regex |
8
|
|
|
*/ |
9
|
|
|
final class Quoter |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Converts browscap match patterns into preg match patterns. |
13
|
|
|
* |
14
|
|
|
* @param string $user_agent |
15
|
|
|
* @param string $delimiter |
16
|
|
|
* |
17
|
|
|
* @return string |
18
|
|
|
*/ |
19
|
1 |
|
public function pregQuote(string $user_agent, string $delimiter = '/') : string |
20
|
|
|
{ |
21
|
1 |
|
$pattern = preg_quote($user_agent, $delimiter); |
22
|
|
|
|
23
|
|
|
// the \\x replacement is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match |
24
|
1 |
|
return str_replace(['\*', '\?', '\\x'], ['.*', '.', '\\\\x'], $pattern); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Reverts the quoting of a pattern. |
29
|
|
|
* |
30
|
|
|
* @param string $pattern |
31
|
|
|
* @return string |
32
|
|
|
*/ |
33
|
|
|
public function pregUnQuote(string $pattern) : string |
34
|
|
|
{ |
35
|
|
|
// Fast check, because most parent pattern like 'DefaultProperties' don't need a replacement |
36
|
|
|
if (preg_match('/[^a-z\s]/i', $pattern)) { |
37
|
|
|
// Undo the \\x replacement, that is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match |
38
|
|
|
// @source https://github.com/browscap/browscap-php |
39
|
|
|
$pattern = preg_replace( |
40
|
|
|
['/(?<!\\\\)\\.\\*/', '/(?<!\\\\)\\./', '/(?<!\\\\)\\\\x/'], |
41
|
|
|
['\\*', '\\?', '\\x'], |
42
|
|
|
$pattern |
43
|
|
|
); |
44
|
|
|
|
45
|
|
|
// Undo preg_quote |
46
|
|
|
$pattern = str_replace( |
47
|
|
|
[ |
48
|
|
|
'\\\\', '\\+', '\\*', '\\?', '\\[', '\\^', '\\]', '\\$', '\\(', '\\)', '\\{', '\\}', '\\=', |
49
|
|
|
'\\!', '\\<', '\\>', '\\|', '\\:', '\\-', '\\.', '\\/', |
50
|
|
|
], |
51
|
|
|
[ |
52
|
|
|
'\\', '+', '*', '?', '[', '^', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', |
53
|
|
|
'-', '.', '/', |
54
|
|
|
], |
55
|
|
|
$pattern |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $pattern; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|