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

nette / utils / 5707056869

pending completion
5707056869

push

github

dg
support for PHP 8.3

3 of 3 new or added lines in 1 file covered. (100.0%)

1580 of 1753 relevant lines covered (90.13%)

0.9 hits per line

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

87.44
/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 is_array, is_object, strlen;
15

16

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

24
        public const TRIM_CHARACTERS = " \t\n\r\0\x0B\u{A0}";
25

26

27
        /**
28
         * Checks if the string is valid in UTF-8 encoding.
29
         */
30
        public static function checkEncoding(string $s): bool
1✔
31
        {
32
                return $s === self::fixEncoding($s);
1✔
33
        }
34

35

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

45

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

58
                return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
1✔
59
        }
60

61

62
        /**
63
         * Starts the $haystack string with the prefix $needle?
64
         */
65
        public static function startsWith(string $haystack, string $needle): bool
1✔
66
        {
67
                return strncmp($haystack, $needle, strlen($needle)) === 0;
1✔
68
        }
69

70

71
        /**
72
         * Ends the $haystack string with the suffix $needle?
73
         */
74
        public static function endsWith(string $haystack, string $needle): bool
1✔
75
        {
76
                return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
1✔
77
        }
78

79

80
        /**
81
         * Does $haystack contain $needle?
82
         */
83
        public static function contains(string $haystack, string $needle): bool
1✔
84
        {
85
                return strpos($haystack, $needle) !== false;
1✔
86
        }
87

88

89
        /**
90
         * Returns a part of UTF-8 string specified by starting position and length. If start is negative,
91
         * the returned string will start at the start'th character from the end of string.
92
         */
93
        public static function substring(string $s, int $start, ?int $length = null): string
1✔
94
        {
95
                if (function_exists('mb_substr')) {
1✔
96
                        return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster
1✔
97
                } elseif (!extension_loaded('iconv')) {
×
98
                        throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.');
×
99
                } elseif ($length === null) {
×
100
                        $length = self::length($s);
×
101
                } elseif ($start < 0 && $length < 0) {
×
102
                        $start += self::length($s); // unifies iconv_substr behavior with mb_substr
×
103
                }
104

105
                return iconv_substr($s, $start, $length, 'UTF-8');
×
106
        }
107

108

109
        /**
110
         * Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines,
111
         * trims end spaces on lines, normalizes UTF-8 to the normal form of NFC.
112
         */
113
        public static function normalize(string $s): string
1✔
114
        {
115
                // convert to compressed normal form (NFC)
116
                if (class_exists('Normalizer', false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) {
1✔
117
                        $s = $n;
1✔
118
                }
119

120
                $s = self::normalizeNewLines($s);
1✔
121

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

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

128
                // leading and trailing blank lines
129
                $s = trim($s, "\n");
1✔
130

131
                return $s;
1✔
132
        }
133

134

135
        /**
136
         * Standardize line endings to unix-like.
137
         */
138
        public static function normalizeNewLines(string $s): string
1✔
139
        {
140
                return str_replace(["\r\n", "\r"], "\n", $s);
1✔
141
        }
142

143

144
        /**
145
         * Converts UTF-8 string to ASCII, ie removes diacritics etc.
146
         */
147
        public static function toAscii(string $s): string
1✔
148
        {
149
                $iconv = defined('ICONV_IMPL') ? trim(ICONV_IMPL, '"\'') : null;
1✔
150
                static $transliterator = null;
1✔
151
                if ($transliterator === null) {
1✔
152
                        if (class_exists('Transliterator', false)) {
1✔
153
                                $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII');
1✔
154
                        } else {
155
                                trigger_error(__METHOD__ . "(): it is recommended to enable PHP extensions 'intl'.", E_USER_NOTICE);
×
156
                                $transliterator = false;
×
157
                        }
158
                }
159

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

163
                // transliteration (by Transliterator and iconv) is not optimal, replace some characters directly
164
                $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✔
165
                if ($iconv !== 'libiconv') {
1✔
166
                        $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✔
167
                }
168

169
                if ($transliterator) {
1✔
170
                        $s = $transliterator->transliterate($s);
1✔
171
                        // use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ
172
                        if ($iconv === 'glibc') {
1✔
173
                                $s = strtr($s, '?', "\x01"); // temporarily hide ? to distinguish them from the garbage that iconv creates
1✔
174
                                $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
1✔
175
                                $s = str_replace(['?', "\x01"], ['', '?'], $s); // remove garbage and restore ? characters
1✔
176
                        } elseif ($iconv === 'libiconv') {
×
177
                                $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
×
178
                        } else { // null or 'unknown' (#216)
179
                                $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars
1✔
180
                        }
181
                } elseif ($iconv === 'glibc' || $iconv === 'libiconv') {
×
182
                        // temporarily hide these characters to distinguish them from the garbage that iconv creates
183
                        $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06");
×
184
                        if ($iconv === 'glibc') {
×
185
                                // glibc implementation is very limited. transliterate into Windows-1250 and then into ASCII, so most Eastern European characters are preserved
186
                                $s = iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s);
×
187
                                $s = strtr(
×
188
                                        $s,
×
189
                                        "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\x96\xa0\x8b\x97\x9b\xa6\xad\xb7",
×
190
                                        'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.'
×
191
                                );
192
                                $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]);
×
193
                        } else {
194
                                $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
×
195
                        }
196

197
                        // remove garbage that iconv creates during transliteration (eg Ý -> Y')
198
                        $s = str_replace(['`', "'", '"', '^', '~', '?'], '', $s);
×
199
                        // restore temporarily hidden characters
200
                        $s = strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?');
×
201
                } else {
202
                        $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars
×
203
                }
204

205
                return $s;
1✔
206
        }
207

208

209
        /**
210
         * Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters
211
         * except letters of the English alphabet and numbers with a hyphens.
212
         */
213
        public static function webalize(string $s, ?string $charlist = null, bool $lower = true): string
1✔
214
        {
215
                $s = self::toAscii($s);
1✔
216
                if ($lower) {
1✔
217
                        $s = strtolower($s);
1✔
218
                }
219

220
                $s = self::pcre('preg_replace', ['#[^a-z0-9' . ($charlist !== null ? preg_quote($charlist, '#') : '') . ']+#i', '-', $s]);
1✔
221
                $s = trim($s, '-');
1✔
222
                return $s;
1✔
223
        }
224

225

226
        /**
227
         * Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated,
228
         * an ellipsis (or something else set with third argument) is appended to the string.
229
         */
230
        public static function truncate(string $s, int $maxLen, string $append = "\u{2026}"): string
1✔
231
        {
232
                if (self::length($s) > $maxLen) {
1✔
233
                        $maxLen -= self::length($append);
1✔
234
                        if ($maxLen < 1) {
1✔
235
                                return $append;
1✔
236

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

240
                        } else {
241
                                return self::substring($s, 0, $maxLen) . $append;
1✔
242
                        }
243
                }
244

245
                return $s;
1✔
246
        }
247

248

249
        /**
250
         * Indents a multiline text from the left. Second argument sets how many indentation chars should be used,
251
         * while the indent itself is the third argument (*tab* by default).
252
         */
253
        public static function indent(string $s, int $level = 1, string $chars = "\t"): string
1✔
254
        {
255
                if ($level > 0) {
1✔
256
                        $s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level));
1✔
257
                }
258

259
                return $s;
1✔
260
        }
261

262

263
        /**
264
         * Converts all characters of UTF-8 string to lower case.
265
         */
266
        public static function lower(string $s): string
1✔
267
        {
268
                return mb_strtolower($s, 'UTF-8');
1✔
269
        }
270

271

272
        /**
273
         * Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged.
274
         */
275
        public static function firstLower(string $s): string
1✔
276
        {
277
                return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1);
1✔
278
        }
279

280

281
        /**
282
         * Converts all characters of a UTF-8 string to upper case.
283
         */
284
        public static function upper(string $s): string
1✔
285
        {
286
                return mb_strtoupper($s, 'UTF-8');
1✔
287
        }
288

289

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

298

299
        /**
300
         * Converts the first character of every word of a UTF-8 string to upper case and the others to lower case.
301
         */
302
        public static function capitalize(string $s): string
1✔
303
        {
304
                return mb_convert_case($s, MB_CASE_TITLE, 'UTF-8');
1✔
305
        }
306

307

308
        /**
309
         * Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared,
310
         * if it is negative, the corresponding number of characters from the end of the strings is compared,
311
         * otherwise the appropriate number of characters from the beginning is compared.
312
         */
313
        public static function compare(string $left, string $right, ?int $length = null): bool
1✔
314
        {
315
                if (class_exists('Normalizer', false)) {
1✔
316
                        $left = \Normalizer::normalize($left, \Normalizer::FORM_D); // form NFD is faster
1✔
317
                        $right = \Normalizer::normalize($right, \Normalizer::FORM_D); // form NFD is faster
1✔
318
                }
319

320
                if ($length < 0) {
1✔
321
                        $left = self::substring($left, $length, -$length);
1✔
322
                        $right = self::substring($right, $length, -$length);
1✔
323
                } elseif ($length !== null) {
1✔
324
                        $left = self::substring($left, 0, $length);
1✔
325
                        $right = self::substring($right, 0, $length);
1✔
326
                }
327

328
                return self::lower($left) === self::lower($right);
1✔
329
        }
330

331

332
        /**
333
         * Finds the common prefix of strings or returns empty string if the prefix was not found.
334
         * @param  string[]  $strings
335
         */
336
        public static function findPrefix(array $strings): string
1✔
337
        {
338
                $first = array_shift($strings);
1✔
339
                for ($i = 0; $i < strlen($first); $i++) {
1✔
340
                        foreach ($strings as $s) {
1✔
341
                                if (!isset($s[$i]) || $first[$i] !== $s[$i]) {
1✔
342
                                        while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") {
1✔
343
                                                $i--;
1✔
344
                                        }
345

346
                                        return substr($first, 0, $i);
1✔
347
                                }
348
                        }
349
                }
350

351
                return $first;
1✔
352
        }
353

354

355
        /**
356
         * Returns number of characters (not bytes) in UTF-8 string.
357
         * That is the number of Unicode code points which may differ from the number of graphemes.
358
         */
359
        public static function length(string $s): int
1✔
360
        {
361
                return function_exists('mb_strlen')
1✔
362
                        ? mb_strlen($s, 'UTF-8')
1✔
363
                        : strlen(utf8_decode($s));
1✔
364
        }
365

366

367
        /**
368
         * Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string.
369
         */
370
        public static function trim(string $s, string $charlist = self::TRIM_CHARACTERS): string
1✔
371
        {
372
                $charlist = preg_quote($charlist, '#');
1✔
373
                return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du', '');
1✔
374
        }
375

376

377
        /**
378
         * Pads a UTF-8 string to given length by prepending the $pad string to the beginning.
379
         * @param  non-empty-string  $pad
380
         */
381
        public static function padLeft(string $s, int $length, string $pad = ' '): string
1✔
382
        {
383
                $length = max(0, $length - self::length($s));
1✔
384
                $padLen = self::length($pad);
1✔
385
                return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s;
1✔
386
        }
387

388

389
        /**
390
         * Pads UTF-8 string to given length by appending the $pad string to the end.
391
         * @param  non-empty-string  $pad
392
         */
393
        public static function padRight(string $s, int $length, string $pad = ' '): string
1✔
394
        {
395
                $length = max(0, $length - self::length($s));
1✔
396
                $padLen = self::length($pad);
1✔
397
                return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen);
1✔
398
        }
399

400

401
        /**
402
         * Reverses UTF-8 string.
403
         */
404
        public static function reverse(string $s): string
1✔
405
        {
406
                if (!extension_loaded('iconv')) {
1✔
407
                        throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
×
408
                }
409

410
                return iconv('UTF-32LE', 'UTF-8', strrev(iconv('UTF-8', 'UTF-32BE', $s)));
1✔
411
        }
412

413

414
        /**
415
         * Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found.
416
         * Negative value means searching from the end.
417
         */
418
        public static function before(string $haystack, string $needle, int $nth = 1): ?string
1✔
419
        {
420
                $pos = self::pos($haystack, $needle, $nth);
1✔
421
                return $pos === null
1✔
422
                        ? null
1✔
423
                        : substr($haystack, 0, $pos);
1✔
424
        }
425

426

427
        /**
428
         * Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found.
429
         * Negative value means searching from the end.
430
         */
431
        public static function after(string $haystack, string $needle, int $nth = 1): ?string
1✔
432
        {
433
                $pos = self::pos($haystack, $needle, $nth);
1✔
434
                return $pos === null
1✔
435
                        ? null
1✔
436
                        : substr($haystack, $pos + strlen($needle));
1✔
437
        }
438

439

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

452

453
        /**
454
         * Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found.
455
         */
456
        private static function pos(string $haystack, string $needle, int $nth = 1): ?int
1✔
457
        {
458
                if (!$nth) {
1✔
459
                        return null;
1✔
460
                } elseif ($nth > 0) {
1✔
461
                        if ($needle === '') {
1✔
462
                                return 0;
1✔
463
                        }
464

465
                        $pos = 0;
1✔
466
                        while (($pos = strpos($haystack, $needle, $pos)) !== false && --$nth) {
1✔
467
                                $pos++;
1✔
468
                        }
469
                } else {
470
                        $len = strlen($haystack);
1✔
471
                        if ($needle === '') {
1✔
472
                                return $len;
1✔
473
                        } elseif ($len === 0) {
1✔
474
                                return null;
1✔
475
                        }
476

477
                        $pos = $len - 1;
1✔
478
                        while (($pos = strrpos($haystack, $needle, $pos - $len)) !== false && ++$nth) {
1✔
479
                                $pos--;
1✔
480
                        }
481
                }
482

483
                return Helpers::falseToNull($pos);
1✔
484
        }
485

486

487
        /**
488
         * Splits a string into array by the regular expression. Parenthesized expression in the delimiter are captured.
489
         * Parameter $flags can be any combination of PREG_SPLIT_NO_EMPTY and PREG_OFFSET_CAPTURE flags.
490
         */
491
        public static function split(
1✔
492
                string $subject,
493
                #[Language('RegExp')]
494
                string $pattern,
495
                int $flags = 0
496
        ): array
497
        {
498
                return self::pcre('preg_split', [$pattern, $subject, -1, $flags | PREG_SPLIT_DELIM_CAPTURE]);
1✔
499
        }
500

501

502
        /**
503
         * Checks if given string matches a regular expression pattern and returns an array with first found match and each subpattern.
504
         * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags.
505
         */
506
        public static function match(
1✔
507
                string $subject,
508
                #[Language('RegExp')]
509
                string $pattern,
510
                int $flags = 0,
511
                int $offset = 0
512
        ): ?array
513
        {
514
                if ($offset > strlen($subject)) {
1✔
515
                        return null;
1✔
516
                }
517

518
                return self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])
1✔
519
                        ? $m
1✔
520
                        : null;
1✔
521
        }
522

523

524
        /**
525
         * Finds all occurrences matching regular expression pattern and returns a two-dimensional array. Result is array of matches (ie uses by default PREG_SET_ORDER).
526
         * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL and PREG_PATTERN_ORDER flags.
527
         */
528
        public static function matchAll(
1✔
529
                string $subject,
530
                #[Language('RegExp')]
531
                string $pattern,
532
                int $flags = 0,
533
                int $offset = 0
534
        ): array
535
        {
536
                if ($offset > strlen($subject)) {
1✔
537
                        return [];
1✔
538
                }
539

540
                self::pcre('preg_match_all', [
1✔
541
                        $pattern, $subject, &$m,
1✔
542
                        ($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER),
1✔
543
                        $offset,
1✔
544
                ]);
545
                return $m;
1✔
546
        }
547

548

549
        /**
550
         * Replaces all occurrences matching regular expression $pattern which can be string or array in the form `pattern => replacement`.
551
         * @param  string|array  $pattern
552
         * @param  string|callable  $replacement
553
         */
554
        public static function replace(
1✔
555
                string $subject,
556
                #[Language('RegExp')]
557
                $pattern,
558
                $replacement = '',
559
                int $limit = -1
560
        ): string
561
        {
562
                if (is_object($replacement) || is_array($replacement)) {
1✔
563
                        if (!is_callable($replacement, false, $textual)) {
1✔
564
                                throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
1✔
565
                        }
566

567
                        return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]);
1✔
568

569
                } elseif (is_array($pattern) && is_string(key($pattern))) {
1✔
570
                        $replacement = array_values($pattern);
1✔
571
                        $pattern = array_keys($pattern);
1✔
572
                }
573

574
                return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]);
1✔
575
        }
576

577

578
        /** @internal */
579
        public static function pcre(string $func, array $args)
1✔
580
        {
581
                $res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void {
1✔
582
                        // compile-time error, not detectable by preg_last_error
583
                        throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0]));
1✔
584
                });
1✔
585

586
                if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars
1✔
587
                        && ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], true))
1✔
588
                ) {
589
                        throw new RegexpException((RegexpException::MESSAGES[$code] ?? 'Unknown error')
1✔
590
                                . ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code);
1✔
591
                }
592

593
                return $res;
1✔
594
        }
595
}
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