• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / utils / 21938400483

12 Feb 2026 08:03AM UTC coverage: 93.193% (-0.2%) from 93.429%
21938400483

push

github

dg
added CLAUDE.md

2081 of 2233 relevant lines covered (93.19%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.79
/src/Utils/Strings.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\Utils;
11

12
use JetBrains\PhpStorm\Language;
13
use Nette;
14
use function array_keys, array_map, array_shift, array_values, bin2hex, class_exists, defined, extension_loaded, function_exists, htmlspecialchars, htmlspecialchars_decode, iconv, iconv_strlen, iconv_substr, implode, in_array, is_array, is_callable, is_int, is_object, is_string, key, max, mb_convert_case, mb_strlen, mb_strtolower, mb_strtoupper, mb_substr, pack, preg_last_error, preg_last_error_msg, preg_quote, preg_replace, str_contains, str_ends_with, str_repeat, str_replace, str_starts_with, strlen, strpos, strrev, strrpos, strtolower, strtoupper, strtr, substr, trim, unpack, utf8_decode;
15
use const ENT_IGNORE, ENT_NOQUOTES, ICONV_IMPL, MB_CASE_TITLE, PHP_EOL, PREG_OFFSET_CAPTURE, PREG_PATTERN_ORDER, PREG_SET_ORDER, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_NO_EMPTY, PREG_SPLIT_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL;
16

17

18
/**
19
 * String tools library.
20
 */
21
class Strings
22
{
23
        use Nette\StaticClass;
24

25
        public const TrimCharacters = " \t\n\r\0\x0B\u{A0}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{200B}\u{2028}\u{3000}";
26

27
        #[\Deprecated('use Strings::TrimCharacters')]
28
        public const TRIM_CHARACTERS = self::TrimCharacters;
29

30

31
        /**
32
         * @deprecated use Nette\Utils\Validators::isUnicode()
33
         */
34
        public static function checkEncoding(string $s): bool
1✔
35
        {
36
                return $s === self::fixEncoding($s);
1✔
37
        }
38

39

40
        /**
41
         * Removes all invalid UTF-8 characters from a string.
42
         */
43
        public static function fixEncoding(string $s): string
1✔
44
        {
45
                // removes xD800-xDFFF, x110000 and higher
46
                return htmlspecialchars_decode(htmlspecialchars($s, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES);
1✔
47
        }
48

49

50
        /**
51
         * Returns a specific character in UTF-8 from code point (number in range 0x0000..D7FF or 0xE000..10FFFF).
52
         * @throws Nette\InvalidArgumentException if code point is not in valid range
53
         */
54
        public static function chr(int $code): string
1✔
55
        {
56
                if ($code < 0 || ($code >= 0xD800 && $code <= 0xDFFF) || $code > 0x10FFFF) {
1✔
57
                        throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.');
1✔
58
                } elseif (!extension_loaded('iconv')) {
1✔
59
                        throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
×
60
                }
61

62
                $res = iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
1✔
63
                return $res === false ? throw new Nette\ShouldNotHappenException : $res;
1✔
64
        }
65

66

67
        /**
68
         * Returns a code point of specific character in UTF-8 (number in range 0x0000..D7FF or 0xE000..10FFFF).
69
         */
70
        public static function ord(string $c): int
1✔
71
        {
72
                if (!extension_loaded('iconv')) {
1✔
73
                        throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
×
74
                }
75

76
                $tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c);
1✔
77
                if ($tmp === false || $tmp === '') {
1✔
78
                        throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".');
1✔
79
                }
80

81
                return unpack('N', $tmp)[1] ?? throw new Nette\ShouldNotHappenException;
1✔
82
        }
83

84

85
        /**
86
         * @deprecated use str_starts_with()
87
         */
88
        public static function startsWith(string $haystack, string $needle): bool
1✔
89
        {
90
                return str_starts_with($haystack, $needle);
1✔
91
        }
92

93

94
        /**
95
         * @deprecated use str_ends_with()
96
         */
97
        public static function endsWith(string $haystack, string $needle): bool
1✔
98
        {
99
                return str_ends_with($haystack, $needle);
1✔
100
        }
101

102

103
        /**
104
         * @deprecated use str_contains()
105
         */
106
        public static function contains(string $haystack, string $needle): bool
1✔
107
        {
108
                return str_contains($haystack, $needle);
1✔
109
        }
110

111

112
        /**
113
         * Returns a part of UTF-8 string specified by starting position and length. If start is negative,
114
         * the returned string will start at the start'th character from the end of string.
115
         */
116
        public static function substring(string $s, int $start, ?int $length = null): string
1✔
117
        {
118
                if (function_exists('mb_substr')) {
1✔
119
                        return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster
1✔
120
                } elseif (!extension_loaded('iconv')) {
×
121
                        throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.');
×
122
                } elseif ($length === null) {
×
123
                        $length = self::length($s);
×
124
                } elseif ($start < 0 && $length < 0) {
×
125
                        $start += self::length($s); // unifies iconv_substr behavior with mb_substr
×
126
                }
127

128
                $res = iconv_substr($s, $start, $length, 'UTF-8');
×
129
                return $res === false ? throw new Nette\InvalidStateException('iconv_substr() failed.') : $res;
×
130
        }
131

132

133
        /**
134
         * Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines,
135
         * trims end spaces on lines, normalizes UTF-8 to the normal form of NFC.
136
         */
137
        public static function normalize(string $s): string
1✔
138
        {
139
                // convert to compressed normal form (NFC)
140
                if (class_exists('Normalizer', autoload: false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) {
1✔
141
                        $s = $n;
1✔
142
                }
143

144
                $s = self::unixNewLines($s);
1✔
145

146
                // remove control characters; leave \t + \n
147
                $s = self::pcre('preg_replace', ['#[\x00-\x08\x0B-\x1F\x7F-\x9F]+#u', '', $s]);
1✔
148

149
                // right trim
150
                $s = self::pcre('preg_replace', ['#[\t ]+$#m', '', $s]);
1✔
151

152
                // leading and trailing blank lines
153
                $s = trim($s, "\n");
1✔
154

155
                return $s;
1✔
156
        }
157

158

159
        /** @deprecated use Strings::unixNewLines() */
160
        public static function normalizeNewLines(string $s): string
1✔
161
        {
162
                return self::unixNewLines($s);
1✔
163
        }
164

165

166
        /**
167
         * Converts line endings to \n used on Unix-like systems.
168
         * Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator.
169
         */
170
        public static function unixNewLines(string $s): string
1✔
171
        {
172
                return preg_replace("~\r\n?|\u{2028}|\u{2029}~", "\n", $s);
1✔
173
        }
174

175

176
        /**
177
         * Converts line endings to platform-specific, i.e. \r\n on Windows and \n elsewhere.
178
         * Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator.
179
         */
180
        public static function platformNewLines(string $s): string
1✔
181
        {
182
                return preg_replace("~\r\n?|\n|\u{2028}|\u{2029}~", PHP_EOL, $s);
1✔
183
        }
184

185

186
        /**
187
         * Converts UTF-8 string to ASCII, ie removes diacritics etc.
188
         */
189
        public static function toAscii(string $s): string
1✔
190
        {
191
                if (!extension_loaded('intl')) {
1✔
192
                        throw new Nette\NotSupportedException(__METHOD__ . '() requires INTL extension that is not loaded.');
×
193
                }
194

195
                $iconv = defined('ICONV_IMPL') ? trim(ICONV_IMPL, '"\'') : null;
1✔
196

197
                // remove control characters and check UTF-8 validity
198
                $s = self::pcre('preg_replace', ['#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s]);
1✔
199

200
                // transliteration (by Transliterator and iconv) is not optimal, replace some characters directly
201
                $s = strtr($s, ["\u{201E}" => '"', "\u{201C}" => '"', "\u{201D}" => '"', "\u{201A}" => "'", "\u{2018}" => "'", "\u{2019}" => "'", "\u{B0}" => '^', "\u{42F}" => 'Ya', "\u{44F}" => 'ya', "\u{42E}" => 'Yu', "\u{44E}" => 'yu', "\u{c4}" => 'Ae', "\u{d6}" => 'Oe', "\u{dc}" => 'Ue', "\u{1e9e}" => 'Ss', "\u{e4}" => 'ae', "\u{f6}" => 'oe', "\u{fc}" => 'ue', "\u{df}" => 'ss']); // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß
1✔
202
                if ($iconv !== 'libiconv') {
1✔
203
                        $s = strtr($s, ["\u{AE}" => '(R)', "\u{A9}" => '(c)', "\u{2026}" => '...', "\u{AB}" => '<<', "\u{BB}" => '>>', "\u{A3}" => 'lb', "\u{A5}" => 'yen', "\u{B2}" => '^2', "\u{B3}" => '^3', "\u{B5}" => 'u', "\u{B9}" => '^1', "\u{BA}" => 'o', "\u{BF}" => '?', "\u{2CA}" => "'", "\u{2CD}" => '_', "\u{2DD}" => '"', "\u{1FEF}" => '', "\u{20AC}" => 'EUR', "\u{2122}" => 'TM', "\u{212E}" => 'e', "\u{2190}" => '<-', "\u{2191}" => '^', "\u{2192}" => '->', "\u{2193}" => 'V', "\u{2194}" => '<->']); // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔
1✔
204
                }
205

206
                $s = \Transliterator::create('Any-Latin; Latin-ASCII')->transliterate($s);
1✔
207
                if ($s === false) {
1✔
208
                        throw new Nette\InvalidStateException('Transliterator::transliterate() failed.');
×
209
                }
210
                // use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ
211
                if ($iconv === 'glibc') {
1✔
212
                        $s = strtr($s, '?', "\x01"); // temporarily hide ? to distinguish them from the garbage that iconv creates
1✔
213
                        $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
1✔
214
                        if ($s === false) {
1✔
215
                                throw new Nette\InvalidStateException('iconv() failed.');
×
216
                        }
217

218
                        $s = str_replace(['?', "\x01"], ['', '?'], $s); // remove garbage and restore ? characters
1✔
219
                } elseif ($iconv === 'libiconv') {
×
220
                        $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
×
221
                        if ($s === false) {
×
222
                                throw new Nette\InvalidStateException('iconv() failed.');
×
223
                        }
224
                } else { // null or 'unknown' (#216)
225
                        $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars
×
226
                }
227

228
                return $s;
1✔
229
        }
230

231

232
        /**
233
         * Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters
234
         * except letters of the English alphabet and numbers with a hyphens.
235
         */
236
        public static function webalize(string $s, ?string $charlist = null, bool $lower = true): string
1✔
237
        {
238
                $s = self::toAscii($s);
1✔
239
                if ($lower) {
1✔
240
                        $s = strtolower($s);
1✔
241
                }
242

243
                $s = self::pcre('preg_replace', ['#[^a-z0-9' . ($charlist !== null ? preg_quote($charlist, '#') : '') . ']+#i', '-', $s]);
1✔
244
                $s = trim($s, '-');
1✔
245
                return $s;
1✔
246
        }
247

248

249
        /**
250
         * Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated,
251
         * an ellipsis (or something else set with third argument) is appended to the string.
252
         */
253
        public static function truncate(string $s, int $maxLen, string $append = "\u{2026}"): string
1✔
254
        {
255
                if (self::length($s) > $maxLen) {
1✔
256
                        $maxLen -= self::length($append);
1✔
257
                        if ($maxLen < 1) {
1✔
258
                                return $append;
1✔
259

260
                        } elseif ($matches = self::match($s, '#^.{1,' . $maxLen . '}(?=[\s\x00-/:-@\[-`{-~])#us')) {
1✔
261
                                return $matches[0] . $append;
1✔
262

263
                        } else {
264
                                return self::substring($s, 0, $maxLen) . $append;
1✔
265
                        }
266
                }
267

268
                return $s;
1✔
269
        }
270

271

272
        /**
273
         * Indents a multiline text from the left. Second argument sets how many indentation chars should be used,
274
         * while the indent itself is the third argument (*tab* by default).
275
         */
276
        public static function indent(string $s, int $level = 1, string $chars = "\t"): string
1✔
277
        {
278
                if ($level > 0) {
1✔
279
                        $s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level));
1✔
280
                }
281

282
                return $s;
1✔
283
        }
284

285

286
        /**
287
         * Converts all characters of UTF-8 string to lower case.
288
         */
289
        public static function lower(string $s): string
1✔
290
        {
291
                return mb_strtolower($s, 'UTF-8');
1✔
292
        }
293

294

295
        /**
296
         * Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged.
297
         */
298
        public static function firstLower(string $s): string
1✔
299
        {
300
                return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1);
1✔
301
        }
302

303

304
        /**
305
         * Converts all characters of a UTF-8 string to upper case.
306
         */
307
        public static function upper(string $s): string
1✔
308
        {
309
                return mb_strtoupper($s, 'UTF-8');
1✔
310
        }
311

312

313
        /**
314
         * Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged.
315
         */
316
        public static function firstUpper(string $s): string
1✔
317
        {
318
                return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1);
1✔
319
        }
320

321

322
        /**
323
         * Converts the first character of every word of a UTF-8 string to upper case and the others to lower case.
324
         */
325
        public static function capitalize(string $s): string
1✔
326
        {
327
                return mb_convert_case($s, MB_CASE_TITLE, 'UTF-8');
1✔
328
        }
329

330

331
        /**
332
         * Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared,
333
         * if it is negative, the corresponding number of characters from the end of the strings is compared,
334
         * otherwise the appropriate number of characters from the beginning is compared.
335
         */
336
        public static function compare(string $left, string $right, ?int $length = null): bool
1✔
337
        {
338
                if (class_exists('Normalizer', autoload: false)) {
1✔
339
                        $left = \Normalizer::normalize($left, \Normalizer::FORM_D); // form NFD is faster
1✔
340
                        $right = \Normalizer::normalize($right, \Normalizer::FORM_D); // form NFD is faster
1✔
341
                }
342

343
                if ($length < 0) {
1✔
344
                        $left = self::substring($left, $length, -$length);
1✔
345
                        $right = self::substring($right, $length, -$length);
1✔
346
                } elseif ($length !== null) {
1✔
347
                        $left = self::substring($left, 0, $length);
1✔
348
                        $right = self::substring($right, 0, $length);
1✔
349
                }
350

351
                return self::lower($left) === self::lower($right);
1✔
352
        }
353

354

355
        /**
356
         * Finds the common prefix of strings or returns empty string if the prefix was not found.
357
         * @param  string[]  $strings
358
         */
359
        public static function findPrefix(array $strings): string
1✔
360
        {
361
                $first = array_shift($strings);
1✔
362
                for ($i = 0; $i < strlen($first); $i++) {
1✔
363
                        foreach ($strings as $s) {
1✔
364
                                if (!isset($s[$i]) || $first[$i] !== $s[$i]) {
1✔
365
                                        while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") {
1✔
366
                                                $i--;
1✔
367
                                        }
368

369
                                        return substr($first, 0, $i);
1✔
370
                                }
371
                        }
372
                }
373

374
                return $first;
1✔
375
        }
376

377

378
        /**
379
         * Returns number of characters (not bytes) in UTF-8 string.
380
         * That is the number of Unicode code points which may differ from the number of graphemes.
381
         */
382
        public static function length(string $s): int
1✔
383
        {
384
                return match (true) {
385
                        extension_loaded('mbstring') => (int) mb_strlen($s, 'UTF-8'),
1✔
386
                        extension_loaded('iconv') => (int) iconv_strlen($s, 'UTF-8'),
×
387
                        default => strlen(@utf8_decode($s)), // deprecated
1✔
388
                };
389
        }
390

391

392
        /**
393
         * Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string.
394
         */
395
        public static function trim(string $s, string $charlist = self::TrimCharacters): string
1✔
396
        {
397
                $charlist = preg_quote($charlist, '#');
1✔
398
                return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du', '');
1✔
399
        }
400

401

402
        /**
403
         * Pads a UTF-8 string to given length by prepending the $pad string to the beginning.
404
         * @param  non-empty-string  $pad
405
         */
406
        public static function padLeft(string $s, int $length, string $pad = ' '): string
1✔
407
        {
408
                $length = max(0, $length - self::length($s));
1✔
409
                $padLen = self::length($pad);
1✔
410
                return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s;
1✔
411
        }
412

413

414
        /**
415
         * Pads UTF-8 string to given length by appending the $pad string to the end.
416
         * @param  non-empty-string  $pad
417
         */
418
        public static function padRight(string $s, int $length, string $pad = ' '): string
1✔
419
        {
420
                $length = max(0, $length - self::length($s));
1✔
421
                $padLen = self::length($pad);
1✔
422
                return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen);
1✔
423
        }
424

425

426
        /**
427
         * Reverses UTF-8 string.
428
         */
429
        public static function reverse(string $s): string
1✔
430
        {
431
                if (!extension_loaded('iconv')) {
1✔
432
                        throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
×
433
                }
434

435
                $tmp = iconv('UTF-8', 'UTF-32BE', $s);
1✔
436
                return $tmp === false
1✔
437
                        ? throw new Nette\InvalidStateException('iconv() failed.')
×
438
                        : (string) iconv('UTF-32LE', 'UTF-8', strrev($tmp));
1✔
439
        }
440

441

442
        /**
443
         * Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found.
444
         * Negative value means searching from the end.
445
         */
446
        public static function before(string $haystack, string $needle, int $nth = 1): ?string
1✔
447
        {
448
                $pos = self::pos($haystack, $needle, $nth);
1✔
449
                return $pos === null
1✔
450
                        ? null
1✔
451
                        : substr($haystack, 0, $pos);
1✔
452
        }
453

454

455
        /**
456
         * Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found.
457
         * Negative value means searching from the end.
458
         */
459
        public static function after(string $haystack, string $needle, int $nth = 1): ?string
1✔
460
        {
461
                $pos = self::pos($haystack, $needle, $nth);
1✔
462
                return $pos === null
1✔
463
                        ? null
1✔
464
                        : substr($haystack, $pos + strlen($needle));
1✔
465
        }
466

467

468
        /**
469
         * Returns position in characters of $nth occurence of $needle in $haystack or null if the $needle was not found.
470
         * Negative value of `$nth` means searching from the end.
471
         */
472
        public static function indexOf(string $haystack, string $needle, int $nth = 1): ?int
1✔
473
        {
474
                $pos = self::pos($haystack, $needle, $nth);
1✔
475
                return $pos === null
1✔
476
                        ? null
1✔
477
                        : self::length(substr($haystack, 0, $pos));
1✔
478
        }
479

480

481
        /**
482
         * Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found.
483
         */
484
        private static function pos(string $haystack, string $needle, int $nth = 1): ?int
1✔
485
        {
486
                if (!$nth) {
1✔
487
                        return null;
1✔
488
                } elseif ($nth > 0) {
1✔
489
                        if ($needle === '') {
1✔
490
                                return 0;
1✔
491
                        }
492

493
                        $pos = 0;
1✔
494
                        while (($pos = strpos($haystack, $needle, $pos)) !== false && --$nth) {
1✔
495
                                $pos++;
1✔
496
                        }
497
                } else {
498
                        $len = strlen($haystack);
1✔
499
                        if ($needle === '') {
1✔
500
                                return $len;
1✔
501
                        } elseif ($len === 0) {
1✔
502
                                return null;
1✔
503
                        }
504

505
                        $pos = $len - 1;
1✔
506
                        while (($pos = strrpos($haystack, $needle, $pos - $len)) !== false && ++$nth) {
1✔
507
                                $pos--;
1✔
508
                        }
509
                }
510

511
                return Helpers::falseToNull($pos);
1✔
512
        }
513

514

515
        /**
516
         * Divides the string into arrays according to the regular expression. Expressions in parentheses will be captured and returned as well.
517
         * @return list<string>
518
         */
519
        public static function split(
1✔
520
                string $subject,
521
                #[Language('RegExp')]
522
                string $pattern,
523
                bool|int $captureOffset = false,
524
                bool $skipEmpty = false,
525
                int $limit = -1,
526
                bool $utf8 = false,
527
        ): array
528
        {
529
                $flags = is_int($captureOffset)  // back compatibility
1✔
530
                        ? $captureOffset
1✔
531
                        : ($captureOffset ? PREG_SPLIT_OFFSET_CAPTURE : 0) | ($skipEmpty ? PREG_SPLIT_NO_EMPTY : 0);
1✔
532

533
                $pattern .= $utf8 ? 'u' : '';
1✔
534
                $m = self::pcre('preg_split', [$pattern, $subject, $limit, $flags | PREG_SPLIT_DELIM_CAPTURE]);
1✔
535
                return $utf8 && $captureOffset
1✔
536
                        ? self::bytesToChars($subject, [$m])[0]
1✔
537
                        : $m;
1✔
538
        }
539

540

541
        /**
542
         * Searches the string for the part matching the regular expression and returns
543
         * an array with the found expression and individual subexpressions, or `null`.
544
         * @return ?array<string>
545
         */
546
        public static function match(
1✔
547
                string $subject,
548
                #[Language('RegExp')]
549
                string $pattern,
550
                bool|int $captureOffset = false,
551
                int $offset = 0,
552
                bool $unmatchedAsNull = false,
553
                bool $utf8 = false,
554
        ): ?array
555
        {
556
                $flags = is_int($captureOffset) // back compatibility
1✔
557
                        ? $captureOffset
1✔
558
                        : ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
1✔
559

560
                if ($utf8) {
1✔
561
                        $offset = strlen(self::substring($subject, 0, $offset));
1✔
562
                        $pattern .= 'u';
1✔
563
                }
564

565
                $m = [];
1✔
566
                if ($offset > strlen($subject)) {
1✔
567
                        return null;
1✔
568
                } elseif (!self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])) {
1✔
569
                        return null;
1✔
570
                } elseif ($utf8 && $captureOffset) {
1✔
571
                        return self::bytesToChars($subject, [$m])[0];
1✔
572
                } else {
573
                        return $m;
1✔
574
                }
575
        }
576

577

578
        /**
579
         * Searches the string for all occurrences matching the regular expression and
580
         * returns an array of arrays containing the found expression and each subexpression.
581
         * @return ($lazy is true ? \Generator<int, array<string>> : list<array<string>>)
582
         */
583
        public static function matchAll(
1✔
584
                string $subject,
585
                #[Language('RegExp')]
586
                string $pattern,
587
                bool|int $captureOffset = false,
588
                int $offset = 0,
589
                bool $unmatchedAsNull = false,
590
                bool $patternOrder = false,
591
                bool $utf8 = false,
592
                bool $lazy = false,
593
        ): array|\Generator
594
        {
595
                if ($utf8) {
1✔
596
                        $offset = strlen(self::substring($subject, 0, $offset));
1✔
597
                        $pattern .= 'u';
1✔
598
                }
599

600
                if ($lazy) {
1✔
601
                        $flags = PREG_OFFSET_CAPTURE | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
1✔
602
                        return (function () use ($utf8, $captureOffset, $flags, $subject, $pattern, $offset) {
1✔
603
                                $counter = 0;
1✔
604
                                $m = null;
1✔
605
                                while (
606
                                        $offset <= strlen($subject) - ($counter ? 1 : 0)
1✔
607
                                        && self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])
1✔
608
                                ) {
609
                                        $offset = $m[0][1] + max(1, strlen($m[0][0]));
1✔
610
                                        if (!$captureOffset) {
1✔
611
                                                $m = array_map(fn($item) => $item[0], $m);
1✔
612
                                        } elseif ($utf8) {
1✔
613
                                                $m = self::bytesToChars($subject, [$m])[0];
1✔
614
                                        }
615
                                        yield $counter++ => $m;
1✔
616
                                }
617
                        })();
1✔
618
                }
619

620
                if ($offset > strlen($subject)) {
1✔
621
                        return [];
1✔
622
                }
623

624
                $flags = is_int($captureOffset) // back compatibility
1✔
625
                        ? $captureOffset
1✔
626
                        : ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0) | ($patternOrder ? PREG_PATTERN_ORDER : 0);
1✔
627

628
                $m = [];
1✔
629
                self::pcre('preg_match_all', [
1✔
630
                        $pattern, $subject, &$m,
1✔
631
                        ($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER),
1✔
632
                        $offset,
1✔
633
                ]);
634
                return $utf8 && $captureOffset
1✔
635
                        ? self::bytesToChars($subject, $m)
1✔
636
                        : $m;
1✔
637
        }
638

639

640
        /**
641
         * Replaces all occurrences matching regular expression $pattern which can be string or array in the form `pattern => replacement`.
642
         * @param  string|array<string, string>  $pattern
643
         */
644
        public static function replace(
1✔
645
                string $subject,
646
                #[Language('RegExp')]
647
                string|array $pattern,
648
                string|callable $replacement = '',
649
                int $limit = -1,
650
                bool $captureOffset = false,
651
                bool $unmatchedAsNull = false,
652
                bool $utf8 = false,
653
        ): string
654
        {
655
                if (is_object($replacement) || is_array($replacement)) {
1✔
656
                        if (!is_callable($replacement, false, $textual)) {
1✔
657
                                throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
×
658
                        }
659

660
                        $flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
1✔
661
                        if ($utf8) {
1✔
662
                                $pattern = is_array($pattern) ? array_map(fn($item) => $item . 'u', $pattern) : $pattern . 'u';
1✔
663
                                if ($captureOffset) {
1✔
664
                                        $replacement = fn($m) => $replacement(self::bytesToChars($subject, [$m])[0]);
1✔
665
                                }
666
                        }
667

668
                        return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]);
1✔
669

670
                } elseif (is_array($pattern) && is_string(key($pattern))) {
1✔
671
                        $replacement = array_values($pattern);
1✔
672
                        $pattern = array_keys($pattern);
1✔
673
                }
674

675
                if ($utf8) {
1✔
676
                        $pattern = array_map(fn($item) => $item . 'u', (array) $pattern);
1✔
677
                }
678

679
                return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]);
1✔
680
        }
681

682

683
        /**
684
         * @param  list<array<array{string, int}>>  $groups
685
         * @return list<array<array{string, int}>>
686
         */
687
        private static function bytesToChars(string $s, array $groups): array
1✔
688
        {
689
                $lastBytes = $lastChars = 0;
1✔
690
                foreach ($groups as &$matches) {
1✔
691
                        foreach ($matches as &$match) {
1✔
692
                                if ($match[1] > $lastBytes) {
1✔
693
                                        $lastChars += self::length(substr($s, $lastBytes, $match[1] - $lastBytes));
1✔
694
                                } elseif ($match[1] < $lastBytes) {
1✔
695
                                        $lastChars -= self::length(substr($s, $match[1], $lastBytes - $match[1]));
1✔
696
                                }
697

698
                                $lastBytes = $match[1];
1✔
699
                                $match[1] = $lastChars;
1✔
700
                        }
701
                }
702

703
                return $groups;
1✔
704
        }
705

706

707
        /**
708
         * @param  callable-string  $func
709
         * @param  list<mixed>  $args
710
         * @internal
711
         */
712
        public static function pcre(string $func, array $args): mixed
1✔
713
        {
714
                $res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void {
1✔
715
                        // compile-time error, not detectable by preg_last_error
716
                        throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0]));
1✔
717
                });
1✔
718

719
                if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars
1✔
720
                        && ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], strict: true))
1✔
721
                ) {
722
                        throw new RegexpException(preg_last_error_msg()
1✔
723
                                . ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code);
1✔
724
                }
725

726
                return $res;
1✔
727
        }
728
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc