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

nette / utils / 22290136219

23 Feb 2026 01:47AM UTC coverage: 93.125% (-0.003%) from 93.128%
22290136219

push

github

dg
added CLAUDE.md

2086 of 2240 relevant lines covered (93.13%)

0.93 hits per line

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

91.45
/src/Utils/Strings.php
1
<?php declare(strict_types=1);
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
namespace Nette\Utils;
9

10
use JetBrains\PhpStorm\Language;
11
use Nette;
12
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;
13
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;
14

15

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

23
        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}";
24

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

28

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

37

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

47

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

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

64

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

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

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

82

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

91

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

100

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

109

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

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

130

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

142
                $s = self::unixNewLines($s);
1✔
143

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

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

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

153
                return $s;
1✔
154
        }
155

156

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

163

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

173

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

183

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

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

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

198
                // transliteration (by Transliterator and iconv) is not optimal, replace some characters directly
199
                $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✔
200
                if ($iconv !== 'libiconv') {
1✔
201
                        $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✔
202
                }
203

204
                $s = \Transliterator::create('Any-Latin; Latin-ASCII')?->transliterate($s)
1✔
205
                        ?? throw new Nette\InvalidStateException('Transliterator::transliterate() failed.');
×
206

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

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

225
                return $s;
1✔
226
        }
227

228

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

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

245

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

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

260
                        } else {
261
                                return self::substring($s, 0, $maxLen) . $append;
1✔
262
                        }
263
                }
264

265
                return $s;
1✔
266
        }
267

268

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

279
                return $s;
1✔
280
        }
281

282

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

291

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

300

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

309

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

318

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

327

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

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

348
                return self::lower($left) === self::lower($right);
1✔
349
        }
350

351

352
        /**
353
         * Finds the common prefix of strings or returns empty string if the prefix was not found.
354
         * @param  string[]  $strings
355
         */
356
        public static function findPrefix(array $strings): string
1✔
357
        {
358
                $first = array_shift($strings);
1✔
359
                if ($first === null) {
1✔
360
                        return '';
×
361
                }
362

363
                for ($i = 0; $i < strlen($first); $i++) {
1✔
364
                        foreach ($strings as $s) {
1✔
365
                                if (!isset($s[$i]) || $first[$i] !== $s[$i]) {
1✔
366
                                        while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") {
1✔
367
                                                $i--;
1✔
368
                                        }
369

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

375
                return $first;
1✔
376
        }
377

378

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

392

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

402

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

414

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

426

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

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

442

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

455

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

468

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

481

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

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

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

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

515

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

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

541

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

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

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

578

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

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

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

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

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

641

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

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

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

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

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

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

684

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

700
                                $lastBytes = $match[1];
1✔
701
                                $match[1] = $lastChars;
1✔
702
                        }
703
                }
704

705
                return $groups;
1✔
706
        }
707

708

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

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

728
                return $res;
1✔
729
        }
730
}
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