Skip to content

Commit fcf270a

Browse files
committed
Add splitWithOffset for PREG_SPLIT_OFFSET_CAPTURE
1 parent 2c0f488 commit fcf270a

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

src/Preg.php

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,11 +189,15 @@ public static function replaceCallbackArray(array $pattern, $subject, $limit = -
189189
* @param string $pattern
190190
* @param string $subject
191191
* @param int $limit
192-
* @param int $flags
192+
* @param int $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE
193193
* @return list<string>
194194
*/
195195
public static function split($pattern, $subject, $limit = -1, $flags = 0)
196196
{
197+
if (($flags & PREG_SPLIT_OFFSET_CAPTURE) !== 0) {
198+
throw new \InvalidArgumentException('PREG_SPLIT_OFFSET_CAPTURE is not supported as it changes the type of $matches, use splitWithOffset() instead');
199+
}
200+
197201
$result = preg_split($pattern, $subject, $limit, $flags);
198202
if ($result === false) {
199203
throw PcreException::fromFunction('preg_split', $pattern);
@@ -202,6 +206,24 @@ public static function split($pattern, $subject, $limit = -1, $flags = 0)
202206
return $result;
203207
}
204208

209+
/**
210+
* @param string $pattern
211+
* @param string $subject
212+
* @param int $limit
213+
* @param int $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE
214+
* @return list<array{string, int}>
215+
* @phpstan-return list<array{string, int<0, max>}>
216+
*/
217+
public static function splitWithOffset($pattern, $subject, $limit = -1, $flags = 0)
218+
{
219+
$result = preg_split($pattern, $subject, $limit, $flags | PREG_SPLIT_OFFSET_CAPTURE);
220+
if ($result === false) {
221+
throw PcreException::fromFunction('preg_split', $pattern);
222+
}
223+
224+
return $result;
225+
}
226+
205227
/**
206228
* @template T of string|\Stringable
207229
* @param string $pattern

0 commit comments

Comments
 (0)