-
-
Notifications
You must be signed in to change notification settings - Fork 166
/
Str.php
1504 lines (1319 loc) · 37.5 KB
/
Str.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Kirby\Toolkit;
use Closure;
use DateTime;
use Exception;
use IntlDateFormatter;
use Kirby\Cms\App;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Query\Query;
use Throwable;
/**
* The String class provides a set
* of handy methods for string
* handling and manipulation.
*
* @package Kirby Toolkit
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Str
{
/**
* Language translation table
*/
public static array $language = [];
/**
* Ascii translation table
*/
public static array $ascii = [
'/°|₀/' => '0',
'/¹|₁/' => '1',
'/²|₂/' => '2',
'/³|₃/' => '3',
'/⁴|₄/' => '4',
'/⁵|₅/' => '5',
'/⁶|₆/' => '6',
'/⁷|₇/' => '7',
'/⁸|₈/' => '8',
'/⁹|₉/' => '9',
'/À|Á|Â|Ã|Å|Ǻ|Ā|Ă|Ą|Ǎ|Ä|A/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|æ|ǽ|ä|a|а/' => 'a',
'/Б/' => 'B',
'/б/' => 'b',
'/Ç|Ć|Ĉ|Ċ|Č|Ц/' => 'C',
'/ç|ć|ĉ|ċ|č|ц/' => 'c',
'/Ð|Ď|Đ/' => 'Dj',
'/ð|ď|đ/' => 'dj',
'/Д/' => 'D',
'/д/' => 'd',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě|Е|Ё|Э/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě|е|ё|э/' => 'e',
'/Ф/' => 'F',
'/ƒ|ф/' => 'f',
'/Ĝ|Ğ|Ġ|Ģ|Г/' => 'G',
'/ĝ|ğ|ġ|ģ|г/' => 'g',
'/Ĥ|Ħ|Х/' => 'H',
'/ĥ|ħ|х/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|И/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|и|i̇/' => 'i',
'/Ĵ|Й/' => 'J',
'/ĵ|й/' => 'j',
'/Ķ|К/' => 'K',
'/ķ|к/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł|Л/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł|л/' => 'l',
'/М/' => 'M',
'/м/' => 'm',
'/Ñ|Ń|Ņ|Ň|Н/' => 'N',
'/ñ|ń|ņ|ň|ʼn|н/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ|Ö|O/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º|ö|o|о/' => 'o',
'/П/' => 'P',
'/п/' => 'p',
'/Ŕ|Ŗ|Ř|Р/' => 'R',
'/ŕ|ŗ|ř|р/' => 'r',
'/Ś|Ŝ|Ş|Ș|Š|С/' => 'S',
'/ś|ŝ|ş|ș|š|ſ|с/' => 's',
'/Ţ|Ț|Ť|Ŧ|Т/' => 'T',
'/ţ|ț|ť|ŧ|т/' => 't',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ|У|Ü|U/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ|у|ü|u/' => 'u',
'/В/' => 'V',
'/в/' => 'v',
'/Ý|Ÿ|Ŷ|Ы/' => 'Y',
'/ý|ÿ|ŷ|ы/' => 'y',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž|З/' => 'Z',
'/ź|ż|ž|з/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/' => 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/Ч/' => 'Ch',
'/ч/' => 'ch',
'/Ю/' => 'Ju',
'/ю/' => 'ju',
'/Я/' => 'Ja',
'/я/' => 'ja',
'/Ш/' => 'Sh',
'/ш/' => 'sh',
'/Щ/' => 'Shch',
'/щ/' => 'shch',
'/Ж/' => 'Zh',
'/ж/' => 'zh',
];
/**
* Default settings for class methods
*/
public static array $defaults = [
'slug' => [
'separator' => '-',
'allowed' => 'a-z0-9'
]
];
/**
* Parse accepted values and their quality from an
* accept string like an Accept or Accept-Language header
*/
public static function accepted(string $input): array
{
$items = [];
// check each type in the Accept header
foreach (static::split($input, ',') as $item) {
$parts = static::split($item, ';');
$value = A::first($parts); // $parts now only contains params
$quality = 1;
// check for the q param ("quality" of the type)
foreach ($parts as $param) {
$param = static::split($param, '=');
if (A::get($param, 0) === 'q' && !empty($param[1])) {
$quality = $param[1];
}
}
$items[$quality][] = $value;
}
// sort items by quality
krsort($items);
$result = [];
foreach ($items as $quality => $values) {
foreach ($values as $value) {
$result[] = [
'quality' => (float)$quality,
'value' => $value
];
}
}
return $result;
}
/**
* Returns the rest of the string after the given substring or character
*/
public static function after(
string $string,
string $needle,
bool $caseInsensitive = false
): string {
$position = static::position($string, $needle, $caseInsensitive);
if ($position === false) {
return '';
}
return static::substr($string, $position + static::length($needle));
}
/**
* Removes the given substring or character
* only from the start of the string
* @since 3.7.0
*/
public static function afterStart(
string $string,
string $needle,
bool $caseInsensitive = false
): string {
if ($needle === '') {
return $string;
}
if (static::startsWith($string, $needle, $caseInsensitive) === true) {
return static::substr($string, static::length($needle));
}
return $string;
}
/**
* Convert a string to 7-bit ASCII.
*/
public static function ascii(string $string): string
{
$string = str_replace(
array_keys(static::$language),
array_values(static::$language),
$string
);
$string = preg_replace(
array_keys(static::$ascii),
array_values(static::$ascii),
$string
);
return preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '', $string);
}
/**
* Returns the beginning of a string before the given substring or character
*/
public static function before(
string $string,
string $needle,
bool $caseInsensitive = false
): string {
$position = static::position($string, $needle, $caseInsensitive);
if ($position === false) {
return '';
}
return static::substr($string, 0, $position);
}
/**
* Removes the given substring or character only from the end of the string
* @since 3.7.0
*/
public static function beforeEnd(
string $string,
string $needle,
bool $caseInsensitive = false
): string {
if ($needle === '') {
return $string;
}
if (static::endsWith($string, $needle, $caseInsensitive) === true) {
return static::substr($string, 0, -static::length($needle));
}
return $string;
}
/**
* Returns everything between two strings from the first occurrence of a given string
*/
public static function between(
string $string = null,
string $start,
string $end
): string {
return static::before(static::after($string, $start), $end);
}
/**
* Converts a string to camel case
*
* @param string $value The string to convert
*/
public static function camel(string $value = null): string
{
return lcfirst(static::studly($value));
}
/**
* Converts a camel-case string to kebab-case
* @since 4.0.0
*
* @param string $value The string to convert
*/
public static function camelToKebab(string $value = null): string
{
return static::lower(preg_replace('!([a-z0-9])([A-Z])!', '$1-$2', $value));
}
/**
* Checks if a str contains another string
*/
public static function contains(
string $string = null,
string $needle,
bool $caseInsensitive = false
): bool {
if ($needle === '') {
return true;
}
$method = $caseInsensitive === true ? 'stripos' : 'strpos';
return call_user_func($method, $string ?? '', $needle) !== false;
}
/**
* Convert timestamp to date string
* according to locale settings
*
* @param 'date'|'intl'|'strftime'|null $handler Custom date handler or `null`
* for the globally configured one
*/
public static function date(
int|null $time = null,
string|IntlDateFormatter $format = null,
string|null $handler = null
): string|int|false {
if (is_null($format) === true) {
return $time;
}
// $format is an IntlDateFormatter instance
if ($format instanceof IntlDateFormatter) {
return $format->format($time ?? time());
}
// automatically determine the handler from global configuration
// if an app instance is already running; otherwise fall back to
// `date` for backwards-compatibility
if ($handler === null) {
$handler = App::instance(null, true)?->option('date.handler') ?? 'date';
}
// `intl` handler
if ($handler === 'intl') {
$datetime = new DateTime();
if ($time !== null) {
$datetime->setTimestamp($time);
}
return IntlDateFormatter::formatObject($datetime, $format);
}
// handle `strftime` to be able
// to suppress deprecation warning
// TODO: remove strftime support for PHP 9.0
if ($handler === 'strftime') {
// make sure timezone is set correctly
date_default_timezone_get();
return @strftime($format, $time);
}
return $handler($format, $time);
}
/**
* Converts a string to a different encoding
*/
public static function convert(
string $string,
string $targetEncoding,
string $sourceEncoding = null
): string {
// detect the source encoding if not passed as third argument
$sourceEncoding ??= static::encoding($string);
// no need to convert if the target encoding is the same
if (strtolower($sourceEncoding) === strtolower($targetEncoding)) {
return $string;
}
return iconv($sourceEncoding, $targetEncoding, $string);
}
/**
* Encode a string (used for email addresses)
*/
public static function encode(string $string): string
{
$encoded = '';
for ($i = 0; $i < static::length($string); $i++) {
$char = static::substr($string, $i, 1);
$char = mb_convert_encoding($char, 'UCS-4BE', 'UTF-8');
list(, $code) = unpack('N', $char);
$encoded .= rand(1, 2) === 1 ? '&#' . $code . ';' : '&#x' . dechex($code) . ';';
}
return $encoded;
}
/**
* Tries to detect the string encoding
*/
public static function encoding(string $string): string
{
return mb_detect_encoding(
$string,
'UTF-8, ISO-8859-1, windows-1251',
true
);
}
/**
* Checks if a string ends with the passed needle
*/
public static function endsWith(
string $string = null,
string $needle,
bool $caseInsensitive = false
): bool {
if ($needle === '') {
return true;
}
$probe = static::substr($string, -static::length($needle));
if ($caseInsensitive === true) {
$needle = static::lower($needle);
$probe = static::lower($probe);
}
return $needle === $probe;
}
/**
* Escape string for context specific output
* @since 3.7.0
*
* @param string $string Untrusted data
* @param string $context Location of output (`html`, `attr`, `js`, `css`, `url` or `xml`)
* @return string Escaped data
*/
public static function esc(
string $string,
string $context = 'html'
): string {
if (method_exists(Escape::class, $context) === true) {
return Escape::$context($string);
}
return $string;
}
/**
* Creates an excerpt of a string
* It removes all html tags first and then cuts the string
* according to the specified number of chars.
*
* @param string $string The string to be shortened
* @param int $chars The final number of characters the string should have
* @param bool $strip True: remove the HTML tags from the string first
* @param string $rep The element, which should be added if the string is too long. Ellipsis is the default.
* @return string The shortened string
*/
public static function excerpt(
string $string,
int $chars = 140,
bool $strip = true,
string $rep = ' …'
): string {
if ($strip === true) {
// ensure that opening tags are preceded by a space, so that
// when tags are skipped we can be sure that words stay separate
$string = preg_replace('#\s*<([^\/])#', ' <${1}', $string);
// in strip mode, we always return plain text
$string = strip_tags($string);
}
// replace line breaks with spaces
$string = str_replace(PHP_EOL, ' ', trim($string));
// remove double spaces
$string = preg_replace('![ ]{2,}!', ' ', $string);
if ($chars === 0) {
return $string;
}
if (static::length($string) <= $chars) {
return $string;
}
// shorten the string to the specified number of characters,
// but make sure to not cut off in the middle of a word
$excerpt = static::substr($string, 0, $chars);
$cutoff = mb_strrpos($excerpt, ' ');
if ($cutoff !== false) {
$excerpt = static::substr($string, 0, $cutoff);
}
return $excerpt . $rep;
}
/**
* Convert the value to a float with a decimal
* point, no matter what the locale setting is
*/
public static function float(
string|int|float|null $value = null
): string {
// make sure $value is not null
$value ??= '';
// turn the value into a string
$value = (string)$value;
// Convert exponential to decimal, 1e-8 as 0.00000001
if (strpos(strtolower($value), 'e') !== false) {
$value = rtrim(sprintf('%.16f', (float)$value), '0');
}
$value = str_replace(',', '.', $value);
$decimal = strrchr($value, '.');
$decimal = match ($decimal) {
false => 0,
default => strlen($decimal) - 1
};
return number_format((float)$value, $decimal, '.', '');
}
/**
* Returns the rest of the string starting from the given character
*/
public static function from(
string $string,
string $needle,
bool $caseInsensitive = false
): string {
$position = static::position($string, $needle, $caseInsensitive);
if ($position === false) {
return '';
}
return static::substr($string, $position);
}
/**
* Adds `-1` to a string or increments the ending number to allow `-2`, `-3`, etc.
* @since 3.7.0
*
* @param string $string The string to increment
* @param int $first Starting number
*/
public static function increment(
string $string,
string $separator = '-',
int $first = 1
): string {
preg_match('/(.+)' . preg_quote($separator, '/') . '([0-9]+)$/', $string, $matches);
if (isset($matches[2]) === true) {
// increment the existing ending number
return $matches[1] . $separator . ((int)$matches[2] + 1);
}
// append a new ending number
return $string . $separator . $first;
}
/**
* Convert a string to kebab case.
*/
public static function kebab(string $value = null): string
{
return static::snake($value, '-');
}
/**
* Convert a kebab case string to camel case.
*/
public static function kebabToCamel(string $value = null): string
{
return ucfirst(preg_replace_callback(
'/-(.)/',
fn ($matches) => strtoupper($matches[1]),
$value ?? ''
));
}
/**
* A UTF-8 safe version of strlen()
*/
public static function length(string $string = null): int
{
return mb_strlen($string ?? '', 'UTF-8');
}
/**
* A UTF-8 safe version of strtolower()
*/
public static function lower(string $string = null): string
{
return mb_strtolower($string ?? '', 'UTF-8');
}
/**
* Safe ltrim alternative
*/
public static function ltrim(string $string, string $trim = ' '): string
{
return preg_replace('!^(' . preg_quote($trim) . ')+!', '', $string);
}
/**
* Match string against a regular expression and return matches
*
* @param string $string The string to match
* @param string $pattern The regular expression
* @param int $flags Optional flags for PHP `preg_match()`
* @param int $offset Positional offset in the string to start the search
* @return array|null The matches or null if no match was found
*/
public static function match(
string $string,
string $pattern,
int $flags = 0,
int $offset = 0
): array|null {
$result = preg_match($pattern, $string, $matches, $flags, $offset);
return ($result === 1) ? $matches : null;
}
/**
* Check whether a string matches a regular expression
*
* @param string $string The string to match
* @param string $pattern The regular expression
* @param int $flags Optional flags for PHP `preg_match()`
* @param int $offset Positional offset in the string to start the search
* @return bool True if the string matches the pattern
*/
public static function matches(
string $string,
string $pattern,
int $flags = 0,
int $offset = 0
): bool {
return static::match($string, $pattern, $flags, $offset) !== null;
}
/**
* Match string against a regular expression and return all matches
*
* @param string $string The string to match
* @param string $pattern The regular expression
* @param int $flags Optional flags for PHP `preg_match_all()`
* @param int $offset Positional offset in the string to start the search
* @return array|null The matches or null if no match was found
*/
public static function matchAll(
string $string,
string $pattern,
int $flags = 0,
int $offset = 0
): array|null {
$result = preg_match_all($pattern, $string, $matches, $flags, $offset);
return ($result > 0) ? $matches : null;
}
/**
* Get a character pool with various possible combinations
*/
public static function pool(
string|array $type,
bool $array = true
): string|array {
if (is_array($type) === true) {
$pool = [];
foreach ($type as $t) {
$pool = array_merge($pool, static::pool($t));
}
} else {
$pool = match (strtolower($type)) {
'alphalower' => range('a', 'z'),
'alphaupper' => range('A', 'Z'),
'alpha' => static::pool(['alphaLower', 'alphaUpper']),
'num' => range(0, 9),
'alphanum' => static::pool(['alpha', 'num']),
'base32' => array_merge(static::pool('alphaUpper'), range(2, 7)),
'base32hex' => array_merge(range(0, 9), range('A', 'V')),
default => []
};
}
return $array ? $pool : implode('', $pool);
}
/**
* Returns the position of a needle in a string
* if it can be found
*
* @throws \Kirby\Exception\InvalidArgumentException for empty $needle
*/
public static function position(
string $string = null,
string $needle,
bool $caseInsensitive = false
): int|false {
if ($needle === '') {
throw new InvalidArgumentException('The needle must not be empty');
}
if ($caseInsensitive === true) {
$string = static::lower($string);
$needle = static::lower($needle);
}
return mb_strpos($string ?? '', $needle, 0, 'UTF-8');
}
/**
* Runs a string query.
* Check out the Query class for more information.
*/
public static function query(string $query, array $data = [])
{
return Query::factory($query)->resolve($data);
}
/**
* Generates a random string that may be used for cryptographic purposes
*
* @param int $length The length of the random string
* @param string $type Pool type (type of allowed characters)
*/
public static function random(
int $length = null,
string $type = 'alphaNum'
): string|false {
$length ??= random_int(5, 10);
$pool = static::pool($type, false);
// catch invalid pools
if (!$pool) {
return false;
}
// regex that matches all characters
// *not* in the pool of allowed characters
$regex = '/[^' . $pool . ']/';
// collect characters until we have our required length
$result = '';
while (($currentLength = strlen($result)) < $length) {
$missing = $length - $currentLength;
$bytes = random_bytes($missing);
$allowed = preg_replace($regex, '', base64_encode($bytes));
$result .= substr($allowed, 0, $missing);
}
return $result;
}
/**
* Replaces all or some occurrences of the search string with the replacement string
* Extension of the str_replace() function in PHP with an additional $limit parameter
*
* @param string|array|Collection $string String being replaced on (haystack); can be an array of multiple subject strings
* @param string|array|Collection $search Value being searched for (needle)
* @param string|array|Collection $replace Value to replace matches with
* @param int|array $limit Maximum possible replacements for each search value;
* multiple limits for each search value are supported;
* defaults to no limit
* @return string|array String with replaced values;
* if $string is an array, array of strings
* @psalm-return ($string is array ? array : string)
*/
public static function replace(
string|array|Collection $string,
string|array|Collection $search,
string|array|Collection $replace,
int|array $limit = -1
): string|array {
// convert Kirby collections to arrays
if ($string instanceof Collection) {
$string = $string->toArray();
}
if ($search instanceof Collection) {
$search = $search->toArray();
}
if ($replace instanceof Collection) {
$replace = $replace->toArray();
}
// without a limit we might as well use the built-in function
if ($limit === -1) {
return str_replace($search, $replace, $string ?? '');
}
// if the limit is zero, the result will be no replacements at all
if ($limit === 0) {
return $string;
}
// multiple subjects are run separately through this method
if (is_array($string) === true) {
$result = [];
foreach ($string as $s) {
$result[] = static::replace($s, $search, $replace, $limit);
}
return $result;
}
// build an array of replacements
// we don't use an associative array because otherwise you couldn't
// replace the same string with different replacements
$replacements = static::replacements($search, $replace, $limit);
// run the string and the replacement array through the replacer
return static::replaceReplacements($string, $replacements);
}
/**
* Generates a replacement array out of dynamic input data
* Used for Str::replace()
*
* @param string|array $search Value being searched for (needle)
* @param string|array $replace Value to replace matches with
* @param int|array $limit Maximum possible replacements for each search value;
* multiple limits for each search value are supported;
* defaults to no limit
* @return array List of replacement arrays, each with a
* 'search', 'replace' and 'limit' attribute
*/
public static function replacements(
string|array $search,
string|array $replace,
int|array $limit
): array {
if (is_array($search) === true) {
$replacements = [];
foreach ($search as $i => $s) {
if (is_array($replace) === true) {
// replace with an empty string if
// no replacement string was defined for this index;
// behavior is identical to official PHP str_replace()
$r = $replace[$i] ?? '';
}
if (is_array($limit) === true) {
// don't apply a limit if no limit
// was defined for this index
$l = $limit[$i] ?? -1;
}
$replacements[] = [
'search' => $s,
'replace' => $r ?? $replace,
'limit' => $l ?? $limit
];
}
return $replacements;
}
if (is_string($replace) === true && is_int($limit) === true) {
return [compact('search', 'replace', 'limit')];
}
throw new InvalidArgumentException('Invalid combination of $search, $replace and $limit params.');
}
/**
* Takes a replacement array and processes the replacements
* Used for Str::replace()
*
* @param string $string String being replaced on (haystack)
* @param array $replacements Replacement array from Str::replacements()
* @return string String with replaced values
*/
public static function replaceReplacements(
string $string,
array $replacements
): string {
// replace in the order of the replacements
// behavior is identical to the official PHP str_replace()
foreach ($replacements as $replacement) {
if (is_int($replacement['limit']) === false) {
throw new Exception('Invalid limit "' . $replacement['limit'] . '".');
}
if ($replacement['limit'] === -1) {
// no limit, we don't need our special replacement routine
$string = str_replace(
$replacement['search'],
$replacement['replace'],
$string
);
continue;
}
if ($replacement['limit'] > 0) {
// limit given, only replace for as many times per replacement
$position = -1;
for ($i = 0; $i < $replacement['limit']; $i++) {
$position = strpos(
$string,
$replacement['search'],
$position + 1
);
if (is_int($position) === true) {
$string = substr_replace(
$string,
$replacement['replace'],
$position,
strlen($replacement['search'])
);
// adapt $pos to the now changed offset
$position = $position + strlen($replacement['replace']) - strlen($replacement['search']);
} else {
// no more match in the string
break;
}
}
}
}
return $string;
}
/**
* Safe rtrim alternative
*/
public static function rtrim(string $string, string $trim = ' '): string
{
return preg_replace('!(' . preg_quote($trim) . ')+$!', '', $string);
}
/**
* Replaces placeholders in string with values from the data array
* and escapes HTML in the results in `{{ }}` placeholders
* while leaving HTML special characters untouched in `{< >}` placeholders
*
* @since 3.6.0
*
* @param string|null $string The string with placeholders
* @param array $data Associative array with placeholders as
* keys and replacements as values.
* Supports query syntax.
* @param array $options An options array that contains:
* - fallback: if a token does not have any matches
* - callback: to be able to handle each matching result (escaping is applied after the callback)
*
* @return string The filled-in and partially escaped string
*/
public static function safeTemplate(
string $string = null,
array $data = [],
array $options = []
): string {
$fallback = $options['fallback'] ?? null;
$callback = $options['callback'] ?? null;
if ($callback instanceof Closure === false) {
$callback = null;
}
// replace and escape
$string = static::template($string, $data, [
'start' => '{{',
'end' => '}}',
'callback' => function ($result, $query, $data) use ($callback) {
if ($callback !== null) {
$result = $callback($result, $query, $data);
}
return Escape::html($result);
},
'fallback' => $fallback
]);
// replace unescaped (specifically marked placeholders)
$string = static::template($string, $data, [
'start' => '{<',
'end' => '>}',
'callback' => $callback,
'fallback' => $fallback
]);
return $string;