Total Complexity | 13 |
Total Lines | 81 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | <?php |
||
5 | class RegexEscaper |
||
6 | { |
||
7 | /** |
||
8 | * @param string $needle |
||
9 | * |
||
10 | * @return string |
||
11 | */ |
||
12 | public static function escapeWholeTextPattern($needle) |
||
13 | { |
||
14 | $escapedNeedle = self::escapeRegularPattern($needle); |
||
15 | $splittedNeedle = Strings::split($escapedNeedle); |
||
16 | |||
17 | $final = ''; |
||
18 | |||
19 | foreach ($splittedNeedle as $index => $letter) { |
||
20 | if ($index === self::getFirstBounduaryPosition($splittedNeedle)) { |
||
21 | $final .= "\\b"; |
||
22 | } |
||
23 | |||
24 | $final .= $letter; |
||
25 | |||
26 | if ($index === self::getLastBounduaryPosition($splittedNeedle)) { |
||
27 | $final .= "\\b"; |
||
28 | } |
||
29 | } |
||
30 | |||
31 | return $final; |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * @param array $splittedNeedle |
||
36 | * |
||
37 | * @return int |
||
38 | */ |
||
39 | private static function getFirstBounduaryPosition($splittedNeedle) |
||
40 | { |
||
41 | for ($i=0; $i < count($splittedNeedle); $i++) { |
||
|
|||
42 | if (self::isBoundary($splittedNeedle[$i])) { |
||
43 | return $i; |
||
44 | } |
||
45 | } |
||
46 | |||
47 | return -1; |
||
48 | } |
||
49 | |||
50 | /** |
||
51 | * @param array $splittedNeedle |
||
52 | * |
||
53 | * @return int |
||
54 | */ |
||
55 | private static function getLastBounduaryPosition($splittedNeedle) |
||
56 | { |
||
57 | for ($i=(count($splittedNeedle)-1); $i >= 0; $i--) { |
||
58 | if (self::isBoundary($splittedNeedle[$i])) { |
||
59 | return $i; |
||
60 | } |
||
61 | } |
||
62 | |||
63 | return -1; |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * @param string $letter |
||
68 | * |
||
69 | * @return bool |
||
70 | */ |
||
71 | private static function isBoundary($letter) |
||
72 | { |
||
73 | return (preg_match("/[\w]/iu", $letter) > 0) ? true : false; |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * @param string $needle |
||
78 | * |
||
79 | * @return string |
||
80 | */ |
||
81 | public static function escapeRegularPattern($needle) |
||
86 | } |
||
87 | } |
||
88 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: