Substringer.php
6.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
<?php
/**
* ====================================================================================================================|
* Компонент, который служит для обрезания строк по заданным параметрам
* ====================================================================================================================|
*/
namespace common\components;
use yii\base\Object;
/**
* Class Substringer
* @package common\components
* ====================================================================================================================|
* @method @static simpleStringSubstring
* @method @static changeStringByRegex
* ====================================================================================================================|
*/
class Substringer extends Object
{
/**
* @param string $haystack
* @param string $needle
* @param bool $reverse
* @return string
*=================================================================================================================|
* @static
* Метод, который берет строку, и обрезает её до заданного момента
*=================================================================================================================|
* @todo
* Пока что метод адекватно работает только при том условии, что нужный нам символ/комбинация символов является
* первой при поисковом запросе, нужно допилить логику, если например:
* $haystack='www.site.com?sort=title_act&sort=category-1&sort=test_val_desc
* то, обрезать всё до нужной комбинации
*=================================================================================================================|
* @example 1
* Start Data:
* $haystack='https://www.youtube.com?v=OBwS66EBUcY
* $needle='?';
* Return result:
* $res='https://www.youtube.com/watch';
* @example 2
* Start data
* $haystack='https://www.youtube.com/watch?v=OBwS66EBUcY';
* $needle ='?';
* $res = '?v=OBwS66EBUcY'
*
*/
public static function simpleStringSubstring(string $haystack, string $needle): string
{
$deletePosition = strpos($haystack, $needle);
if ($deletePosition == 0)
return $haystack;
$result = substr($haystack, 0, $deletePosition);
return $result;
}
/**
* @param string $haystack
* @param string $regex1
* @param string $regex2
* @param string $requiredDelimiter
* @param string $firstConcatenateSymbol
* @param string $secondConcatenateSymbol
* @return string
* ================================================================================================================|
* Метод, который берет $haystack, а так же 2 Regex паттерна
* 1) пытается найти regex совпадения
* если их нет @return original $haystack
* 2) вырезает всё лишнее со строки с помощью self::Substringer
* 3) конкатенирует между собой то,что получилось за принципом
* mainString+delimiter1+regex1Result+delimiter2+regex2Result
* ================================================================================================================|
* @example
* $haystack='https://www.linija-svitla.ua/catalog/ulichnoe-osveshchenie?page_num=3&fcatlist=3268%2C&sort=test_test&3269%2C3270%2C3272%2C3273%2C3274%2C3275&page=50&per-page=18';
* $regex1='/(\??|&?)page=\d{1,5}&per-page=\d{1,5}/';
* $regex2='/(\?|&)sort=[a-zA-z_]+/';
* $requiredDelimiter='?';
* $firstConcatenateSymbol='?';
* $secondConcatenateSymbol='&';
* $res=$this->changeStringByRegex($haystack,$regex1,$regex2,$firstConcatenateSymbol,$secondConcatenateSymbol,$requiredDelimiter);
* @example-return
* https://www.linija-svitla.ua/catalog/ulichnoe-osveshchenie?page=50&per-page=18&sort=test_test
* ================================================================================================================|
* @todo
* 1) Пока что метод работает только с 2 regex,надо будет поменять строго regex string => regex array
* 2) Метод полюбому обрезает первый символ результирующей строки regex
* 3) нужно сделать механизм замены строки только по 1 regex
* ================================================================================================================|
*
*/
/**
* @param string $haystack
* @param string $regex1
* @param string $regex2
* @param string $requiredDelimiter
* @param string $firstConcatenateSymbol
* @param string $secondConcatenateSymbol
*
* @return string
*/
public static function changeStringByRegex(string $haystack, string $regex1, string $regex2, string $requiredDelimiter = '',
string $firstConcatenateSymbol = '',
string $secondConcatenateSymbol = ''
): string
{
# 1 give rexe1/regex2 parts
# IF we have no consilience with both Regex == > return $haystack
if (preg_match($regex1, $haystack) !== 0 || preg_match($regex2, $haystack) !== 0) {
preg_match($regex1, $haystack, $matches[0]);
preg_match($regex2, $haystack, $matches[1]);
} else return $haystack;
# 2 give must part of string
$mustPartOfstring = self::SimpleStringSubstring($haystack, $requiredDelimiter);
# 3 if regex1/regex2 !empty concatenate they with $mustPartOfString
if (isset($matches[0][0]) && isset($matches[1][0])) {
# удаляем первый символ ( прим; $matches[0][0]='&sort=test_desc')
# нам надо только текст без первого спецсимвола
$matches[0][0] = substr($matches[0][0], 1);
$mustPartOfstring = (isset($matches[0][0])) ? $mustPartOfstring . $firstConcatenateSymbol . $matches[0][0] : $mustPartOfstring;
$matches[1][0] = substr($matches[1][0], 1);
$mustPartOfstring = (isset($matches[1][0])) ? $mustPartOfstring . $secondConcatenateSymbol . $matches[1][0] : $mustPartOfstring;
} # если найден только 1й regex
elseif (isset($matches[0][0]) && !isset($matches[1][0])) {
$matches[0][0] = substr($matches[0][0], 1);
$mustPartOfstring = (isset($matches[0][0])) ? $mustPartOfstring . $firstConcatenateSymbol . $matches[0][0] : $mustPartOfstring;
} # если найден 2й regex
elseif (!isset($matches[0][0]) && isset($matches[1][0])) {
$matches[1][0] = substr($matches[1][0], 1);
$mustPartOfstring = (isset($matches[1][0])) ? $mustPartOfstring . $firstConcatenateSymbol . $matches[1][0] : $mustPartOfstring;
}
return $mustPartOfstring;
}
}