@@ 91-115 (lines=25) @@ | ||
88 | * |
|
89 | * @throws PcreException When PCRE Error occurs. |
|
90 | */ |
|
91 | public function regexExtract($pattern, $options = '') |
|
92 | { |
|
93 | // Define the array that will be filled by preg_match(). |
|
94 | $matches = []; |
|
95 | ||
96 | // Ensure the options contain the "u" modifier. |
|
97 | if (!$this->newSelf($options)->contains('u')) $options .= 'u'; |
|
98 | ||
99 | // Build the expression |
|
100 | $expression = |
|
101 | $this->regexDelimiter. |
|
102 | $pattern. |
|
103 | $this->regexDelimiter. |
|
104 | $options |
|
105 | ; |
|
106 | ||
107 | // Run the expression |
|
108 | $result = preg_match($expression, $this->scalarString, $matches); |
|
109 | ||
110 | // If no errors return the $matches array |
|
111 | if ($result !== false) return $this->newSelfs($matches); |
|
112 | ||
113 | // Otherwise throw with last known PCRE Error. |
|
114 | throw new PcreException(); |
|
115 | } |
|
116 | ||
117 | /** |
|
118 | * Replaces all occurrences of $pattern in $str by $replacement. |
|
@@ 130-155 (lines=26) @@ | ||
127 | * |
|
128 | * @throws PcreException When PCRE Error occurs. |
|
129 | */ |
|
130 | public function regexReplace($pattern, $replacement, $options = '') |
|
131 | { |
|
132 | // The original regexReplace method in danielstjules/Stringy used |
|
133 | // mb_ereg_replace() which supports an "r" flag, PCRE does not. |
|
134 | if ($options === 'msr') $options = 'ms'; |
|
135 | ||
136 | // Ensure the options contain the "u" modifier. |
|
137 | if (!$this->newSelf($options)->contains('u')) $options .= 'u'; |
|
138 | ||
139 | // Build the expression |
|
140 | $expression = |
|
141 | $this->regexDelimiter. |
|
142 | $pattern. |
|
143 | $this->regexDelimiter. |
|
144 | $options |
|
145 | ; |
|
146 | ||
147 | // Run the regular expression replacement |
|
148 | $replaced = preg_replace($expression, $replacement, $this->scalarString); |
|
149 | ||
150 | // If no errors return the replacement |
|
151 | if ($replaced !== null) return $this->newSelf($replaced); |
|
152 | ||
153 | // Otherwise throw with last known PCRE Error. |
|
154 | throw new PcreException(); |
|
155 | } |
|
156 | ||
157 | /** |
|
158 | * Splits the string with the provided regular expression. |