-
Notifications
You must be signed in to change notification settings - Fork 162
/
Str.php
2041 lines (1732 loc) · 57.9 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 Illuminate\Support;
use Closure;
use Illuminate\Support\Traits\Macroable;
use JsonException;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension;
use League\CommonMark\GithubFlavoredMarkdownConverter;
use League\CommonMark\MarkdownConverter;
use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Ramsey\Uuid\Generator\CombGenerator;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactory;
use Symfony\Component\Uid\Ulid;
use Throwable;
use Traversable;
use voku\helper\ASCII;
class Str
{
use Macroable;
/**
* The cache of snake-cased words.
*
* @var array
*/
protected static $snakeCache = [];
/**
* The cache of camel-cased words.
*
* @var array
*/
protected static $camelCache = [];
/**
* The cache of studly-cased words.
*
* @var array
*/
protected static $studlyCache = [];
/**
* The callback that should be used to generate UUIDs.
*
* @var callable|null
*/
protected static $uuidFactory;
/**
* The callback that should be used to generate ULIDs.
*
* @var callable|null
*/
protected static $ulidFactory;
/**
* The callback that should be used to generate random strings.
*
* @var callable|null
*/
protected static $randomStringFactory;
/**
* Get a new stringable object from the given string.
*
* @param string $string
* @return \Illuminate\Support\Stringable
*/
public static function of($string)
{
return new Stringable($string);
}
/**
* Return the remainder of a string after the first occurrence of a given value.
*
* @param string $subject
* @param string $search
* @return string
*/
public static function after($subject, $search)
{
return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0];
}
/**
* Return the remainder of a string after the last occurrence of a given value.
*
* @param string $subject
* @param string $search
* @return string
*/
public static function afterLast($subject, $search)
{
if ($search === '') {
return $subject;
}
$position = strrpos($subject, (string) $search);
if ($position === false) {
return $subject;
}
return substr($subject, $position + strlen($search));
}
/**
* Transliterate a UTF-8 value to ASCII.
*
* @param string $value
* @param string $language
* @return string
*/
public static function ascii($value, $language = 'en')
{
return ASCII::to_ascii((string) $value, $language, replace_single_chars_only: false);
}
/**
* Transliterate a string to its closest ASCII representation.
*
* @param string $string
* @param string|null $unknown
* @param bool|null $strict
* @return string
*/
public static function transliterate($string, $unknown = '?', $strict = false)
{
return ASCII::to_transliterate($string, $unknown, $strict);
}
/**
* Get the portion of a string before the first occurrence of a given value.
*
* @param string $subject
* @param string $search
* @return string
*/
public static function before($subject, $search)
{
if ($search === '') {
return $subject;
}
$result = strstr($subject, (string) $search, true);
return $result === false ? $subject : $result;
}
/**
* Get the portion of a string before the last occurrence of a given value.
*
* @param string $subject
* @param string $search
* @return string
*/
public static function beforeLast($subject, $search)
{
if ($search === '') {
return $subject;
}
$pos = mb_strrpos($subject, $search);
if ($pos === false) {
return $subject;
}
return static::substr($subject, 0, $pos);
}
/**
* Get the portion of a string between two given values.
*
* @param string $subject
* @param string $from
* @param string $to
* @return string
*/
public static function between($subject, $from, $to)
{
if ($from === '' || $to === '') {
return $subject;
}
return static::beforeLast(static::after($subject, $from), $to);
}
/**
* Get the smallest possible portion of a string between two given values.
*
* @param string $subject
* @param string $from
* @param string $to
* @return string
*/
public static function betweenFirst($subject, $from, $to)
{
if ($from === '' || $to === '') {
return $subject;
}
return static::before(static::after($subject, $from), $to);
}
/**
* Convert a value to camel case.
*
* @param string $value
* @return string
*/
public static function camel($value)
{
if (isset(static::$camelCache[$value])) {
return static::$camelCache[$value];
}
return static::$camelCache[$value] = lcfirst(static::studly($value));
}
/**
* Get the character at the specified index.
*
* @param string $subject
* @param int $index
* @return string|false
*/
public static function charAt($subject, $index)
{
$length = mb_strlen($subject);
if ($index < 0 ? $index < -$length : $index > $length - 1) {
return false;
}
return mb_substr($subject, $index, 1);
}
/**
* Remove the given string(s) if it exists at the start of the haystack.
*
* @param string $subject
* @param string|array $needle
* @return string
*/
public static function chopStart($subject, $needle)
{
foreach ((array) $needle as $n) {
if (str_starts_with($subject, $n)) {
return substr($subject, strlen($n));
}
}
return $subject;
}
/**
* Remove the given string(s) if it exists at the end of the haystack.
*
* @param string $subject
* @param string|array $needle
* @return string
*/
public static function chopEnd($subject, $needle)
{
foreach ((array) $needle as $n) {
if (str_ends_with($subject, $n)) {
return substr($subject, 0, -strlen($n));
}
}
return $subject;
}
/**
* Determine if a given string contains a given substring.
*
* @param string $haystack
* @param string|iterable<string> $needles
* @param bool $ignoreCase
* @return bool
*/
public static function contains($haystack, $needles, $ignoreCase = false)
{
if ($ignoreCase) {
$haystack = mb_strtolower($haystack);
}
if (! is_iterable($needles)) {
$needles = (array) $needles;
}
foreach ($needles as $needle) {
if ($ignoreCase) {
$needle = mb_strtolower($needle);
}
if ($needle !== '' && str_contains($haystack, $needle)) {
return true;
}
}
return false;
}
/**
* Determine if a given string contains all array values.
*
* @param string $haystack
* @param iterable<string> $needles
* @param bool $ignoreCase
* @return bool
*/
public static function containsAll($haystack, $needles, $ignoreCase = false)
{
foreach ($needles as $needle) {
if (! static::contains($haystack, $needle, $ignoreCase)) {
return false;
}
}
return true;
}
/**
* Determine if a given string doesn't contain a given substring.
*
* @param string $haystack
* @param string|iterable<string> $needles
* @param bool $ignoreCase
* @return bool
*/
public static function doesntContain($haystack, $needles, $ignoreCase = false)
{
return ! static::contains($haystack, $needles, $ignoreCase);
}
/**
* Convert the case of a string.
*
* @param string $string
* @param int $mode
* @param string|null $encoding
* @return string
*/
public static function convertCase(string $string, int $mode = MB_CASE_FOLD, ?string $encoding = 'UTF-8')
{
return mb_convert_case($string, $mode, $encoding);
}
/**
* Replace consecutive instances of a given character with a single character in the given string.
*
* @param string $string
* @param string $character
* @return string
*/
public static function deduplicate(string $string, string $character = ' ')
{
return preg_replace('/'.preg_quote($character, '/').'+/u', $character, $string);
}
/**
* Determine if a given string ends with a given substring.
*
* @param string $haystack
* @param string|iterable<string> $needles
* @return bool
*/
public static function endsWith($haystack, $needles)
{
if (! is_iterable($needles)) {
$needles = (array) $needles;
}
foreach ($needles as $needle) {
if ((string) $needle !== '' && str_ends_with($haystack, $needle)) {
return true;
}
}
return false;
}
/**
* Extracts an excerpt from text that matches the first instance of a phrase.
*
* @param string $text
* @param string $phrase
* @param array $options
* @return string|null
*/
public static function excerpt($text, $phrase = '', $options = [])
{
$radius = $options['radius'] ?? 100;
$omission = $options['omission'] ?? '...';
preg_match('/^(.*?)('.preg_quote((string) $phrase, '/').')(.*)$/iu', (string) $text, $matches);
if (empty($matches)) {
return null;
}
$start = ltrim($matches[1]);
$start = Str::of(mb_substr($start, max(mb_strlen($start, 'UTF-8') - $radius, 0), $radius, 'UTF-8'))->ltrim()->unless(
fn ($startWithRadius) => $startWithRadius->exactly($start),
fn ($startWithRadius) => $startWithRadius->prepend($omission),
);
$end = rtrim($matches[3]);
$end = Str::of(mb_substr($end, 0, $radius, 'UTF-8'))->rtrim()->unless(
fn ($endWithRadius) => $endWithRadius->exactly($end),
fn ($endWithRadius) => $endWithRadius->append($omission),
);
return $start->append($matches[2], $end)->toString();
}
/**
* Cap a string with a single instance of a given value.
*
* @param string $value
* @param string $cap
* @return string
*/
public static function finish($value, $cap)
{
$quoted = preg_quote($cap, '/');
return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap;
}
/**
* Wrap the string with the given strings.
*
* @param string $value
* @param string $before
* @param string|null $after
* @return string
*/
public static function wrap($value, $before, $after = null)
{
return $before.$value.($after ??= $before);
}
/**
* Unwrap the string with the given strings.
*
* @param string $value
* @param string $before
* @param string|null $after
* @return string
*/
public static function unwrap($value, $before, $after = null)
{
if (static::startsWith($value, $before)) {
$value = static::substr($value, static::length($before));
}
if (static::endsWith($value, $after ??= $before)) {
$value = static::substr($value, 0, -static::length($after));
}
return $value;
}
/**
* Determine if a given string matches a given pattern.
*
* @param string|iterable<string> $pattern
* @param string $value
* @return bool
*/
public static function is($pattern, $value)
{
$value = (string) $value;
if (! is_iterable($pattern)) {
$pattern = [$pattern];
}
foreach ($pattern as $pattern) {
$pattern = (string) $pattern;
// If the given value is an exact match we can of course return true right
// from the beginning. Otherwise, we will translate asterisks and do an
// actual pattern match against the two strings to see if they match.
if ($pattern === '*' || $pattern === $value) {
return true;
}
$pattern = preg_quote($pattern, '#');
// Asterisks are translated into zero-or-more regular expression wildcards
// to make it convenient to check if the strings starts with the given
// pattern such as "library/*", making any string check convenient.
$pattern = str_replace('\*', '.*', $pattern);
if (preg_match('#^'.$pattern.'\z#su', $value) === 1) {
return true;
}
}
return false;
}
/**
* Determine if a given string is 7 bit ASCII.
*
* @param string $value
* @return bool
*/
public static function isAscii($value)
{
return ASCII::is_ascii((string) $value);
}
/**
* Determine if a given value is valid JSON.
*
* @param mixed $value
* @return bool
*/
public static function isJson($value)
{
if (! is_string($value)) {
return false;
}
if (function_exists('json_validate')) {
return json_validate($value, 512);
}
try {
json_decode($value, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
return false;
}
return true;
}
/**
* Determine if a given value is a valid URL.
*
* @param mixed $value
* @param array $protocols
* @return bool
*/
public static function isUrl($value, array $protocols = [])
{
if (! is_string($value)) {
return false;
}
$protocolList = empty($protocols)
? 'aaa|aaas|about|acap|acct|acd|acr|adiumxtra|adt|afp|afs|aim|amss|android|appdata|apt|ark|attachment|aw|barion|beshare|bitcoin|bitcoincash|blob|bolo|browserext|calculator|callto|cap|cast|casts|chrome|chrome-extension|cid|coap|coap\+tcp|coap\+ws|coaps|coaps\+tcp|coaps\+ws|com-eventbrite-attendee|content|conti|crid|cvs|dab|data|dav|diaspora|dict|did|dis|dlna-playcontainer|dlna-playsingle|dns|dntp|dpp|drm|drop|dtn|dvb|ed2k|elsi|example|facetime|fax|feed|feedready|file|filesystem|finger|first-run-pen-experience|fish|fm|ftp|fuchsia-pkg|geo|gg|git|gizmoproject|go|gopher|graph|gtalk|h323|ham|hcap|hcp|http|https|hxxp|hxxps|hydrazone|iax|icap|icon|im|imap|info|iotdisco|ipn|ipp|ipps|irc|irc6|ircs|iris|iris\.beep|iris\.lwz|iris\.xpc|iris\.xpcs|isostore|itms|jabber|jar|jms|keyparc|lastfm|ldap|ldaps|leaptofrogans|lorawan|lvlt|magnet|mailserver|mailto|maps|market|message|mid|mms|modem|mongodb|moz|ms-access|ms-browser-extension|ms-calculator|ms-drive-to|ms-enrollment|ms-excel|ms-eyecontrolspeech|ms-gamebarservices|ms-gamingoverlay|ms-getoffice|ms-help|ms-infopath|ms-inputapp|ms-lockscreencomponent-config|ms-media-stream-id|ms-mixedrealitycapture|ms-mobileplans|ms-officeapp|ms-people|ms-project|ms-powerpoint|ms-publisher|ms-restoretabcompanion|ms-screenclip|ms-screensketch|ms-search|ms-search-repair|ms-secondary-screen-controller|ms-secondary-screen-setup|ms-settings|ms-settings-airplanemode|ms-settings-bluetooth|ms-settings-camera|ms-settings-cellular|ms-settings-cloudstorage|ms-settings-connectabledevices|ms-settings-displays-topology|ms-settings-emailandaccounts|ms-settings-language|ms-settings-location|ms-settings-lock|ms-settings-nfctransactions|ms-settings-notifications|ms-settings-power|ms-settings-privacy|ms-settings-proximity|ms-settings-screenrotation|ms-settings-wifi|ms-settings-workplace|ms-spd|ms-sttoverlay|ms-transit-to|ms-useractivityset|ms-virtualtouchpad|ms-visio|ms-walk-to|ms-whiteboard|ms-whiteboard-cmd|ms-word|msnim|msrp|msrps|mss|mtqp|mumble|mupdate|mvn|news|nfs|ni|nih|nntp|notes|ocf|oid|onenote|onenote-cmd|opaquelocktoken|openpgp4fpr|pack|palm|paparazzi|payto|pkcs11|platform|pop|pres|prospero|proxy|pwid|psyc|pttp|qb|query|redis|rediss|reload|res|resource|rmi|rsync|rtmfp|rtmp|rtsp|rtsps|rtspu|s3|secondlife|service|session|sftp|sgn|shttp|sieve|simpleledger|sip|sips|skype|smb|sms|smtp|snews|snmp|soap\.beep|soap\.beeps|soldat|spiffe|spotify|ssh|steam|stun|stuns|submit|svn|tag|teamspeak|tel|teliaeid|telnet|tftp|tg|things|thismessage|tip|tn3270|tool|ts3server|turn|turns|tv|udp|unreal|urn|ut2004|v-event|vemmi|ventrilo|videotex|vnc|view-source|wais|webcal|wpid|ws|wss|wtai|wyciwyg|xcon|xcon-userid|xfire|xmlrpc\.beep|xmlrpc\.beeps|xmpp|xri|ymsgr|z39\.50|z39\.50r|z39\.50s'
: implode('|', $protocols);
/*
* This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (5.0.7).
*
* (c) Fabien Potencier <[email protected]> http://symfony.com
*/
$pattern = '~^
(LARAVEL_PROTOCOLS):// # protocol
(((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+)@)? # basic auth
(
([\pL\pN\pS\-\_\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name
| # or
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address
| # or
\[
(?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::))))
\] # an IPv6 address
)
(:[0-9]+)? # a port (optional)
(?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})* )* # a path
(?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a query (optional)
(?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a fragment (optional)
$~ixu';
return preg_match(str_replace('LARAVEL_PROTOCOLS', $protocolList, $pattern), $value) > 0;
}
/**
* Determine if a given value is a valid UUID.
*
* @param mixed $value
* @param int<0, 8>|'max'|null $version
* @return bool
*/
public static function isUuid($value, $version = null)
{
if (! is_string($value)) {
return false;
}
if ($version === null) {
return preg_match('/^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$/D', $value) > 0;
}
$factory = new UuidFactory;
try {
$factoryUuid = $factory->fromString($value);
} catch (InvalidUuidStringException $ex) {
return false;
}
$fields = $factoryUuid->getFields();
if (! ($fields instanceof FieldsInterface)) {
return false;
}
if ($version === 0 || $version === 'nil') {
return $fields->isNil();
}
if ($version === 'max') {
return $fields->isMax();
}
return $fields->getVersion() === $version;
}
/**
* Determine if a given value is a valid ULID.
*
* @param mixed $value
* @return bool
*/
public static function isUlid($value)
{
if (! is_string($value)) {
return false;
}
return Ulid::isValid($value);
}
/**
* Convert a string to kebab case.
*
* @param string $value
* @return string
*/
public static function kebab($value)
{
return static::snake($value, '-');
}
/**
* Return the length of the given string.
*
* @param string $value
* @param string|null $encoding
* @return int
*/
public static function length($value, $encoding = null)
{
return mb_strlen($value, $encoding);
}
/**
* Limit the number of characters in a string.
*
* @param string $value
* @param int $limit
* @param string $end
* @param bool $preserveWords
* @return string
*/
public static function limit($value, $limit = 100, $end = '...', $preserveWords = false)
{
if (mb_strwidth($value, 'UTF-8') <= $limit) {
return $value;
}
if (! $preserveWords) {
return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
}
$value = trim(preg_replace('/[\n\r]+/', ' ', strip_tags($value)));
$trimmed = rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8'));
if (mb_substr($value, $limit, 1, 'UTF-8') === ' ') {
return $trimmed.$end;
}
return preg_replace("/(.*)\s.*/", '$1', $trimmed).$end;
}
/**
* Convert the given string to lower-case.
*
* @param string $value
* @return string
*/
public static function lower($value)
{
return mb_strtolower($value, 'UTF-8');
}
/**
* Limit the number of words in a string.
*
* @param string $value
* @param int $words
* @param string $end
* @return string
*/
public static function words($value, $words = 100, $end = '...')
{
preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
return $value;
}
return rtrim($matches[0]).$end;
}
/**
* Converts GitHub flavored Markdown into HTML.
*
* @param string $string
* @param array $options
* @param array $extensions
* @return string
*/
public static function markdown($string, array $options = [], array $extensions = [])
{
$converter = new GithubFlavoredMarkdownConverter($options);
$environment = $converter->getEnvironment();
foreach ($extensions as $extension) {
$environment->addExtension($extension);
}
return (string) $converter->convert($string);
}
/**
* Converts inline Markdown into HTML.
*
* @param string $string
* @param array $options
* @param array $extensions
* @return string
*/
public static function inlineMarkdown($string, array $options = [], array $extensions = [])
{
$environment = new Environment($options);
$environment->addExtension(new GithubFlavoredMarkdownExtension());
$environment->addExtension(new InlinesOnlyExtension());
foreach ($extensions as $extension) {
$environment->addExtension($extension);
}
$converter = new MarkdownConverter($environment);
return (string) $converter->convert($string);
}
/**
* Masks a portion of a string with a repeated character.
*
* @param string $string
* @param string $character
* @param int $index
* @param int|null $length
* @param string $encoding
* @return string
*/
public static function mask($string, $character, $index, $length = null, $encoding = 'UTF-8')
{
if ($character === '') {
return $string;
}
$segment = mb_substr($string, $index, $length, $encoding);
if ($segment === '') {
return $string;
}
$strlen = mb_strlen($string, $encoding);
$startIndex = $index;
if ($index < 0) {
$startIndex = $index < -$strlen ? 0 : $strlen + $index;
}
$start = mb_substr($string, 0, $startIndex, $encoding);
$segmentLen = mb_strlen($segment, $encoding);
$end = mb_substr($string, $startIndex + $segmentLen);
return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end;
}
/**
* Get the string matching the given pattern.
*
* @param string $pattern
* @param string $subject
* @return string
*/
public static function match($pattern, $subject)
{
preg_match($pattern, $subject, $matches);
if (! $matches) {
return '';
}
return $matches[1] ?? $matches[0];
}
/**
* Determine if a given string matches a given pattern.
*
* @param string|iterable<string> $pattern
* @param string $value
* @return bool
*/
public static function isMatch($pattern, $value)
{
$value = (string) $value;
if (! is_iterable($pattern)) {
$pattern = [$pattern];
}
foreach ($pattern as $pattern) {
$pattern = (string) $pattern;
if (preg_match($pattern, $value) === 1) {
return true;
}
}
return false;
}
/**
* Get the string matching the given pattern.
*
* @param string $pattern
* @param string $subject
* @return \Illuminate\Support\Collection
*/
public static function matchAll($pattern, $subject)
{
preg_match_all($pattern, $subject, $matches);
if (empty($matches[0])) {
return new Collection;
}
return new Collection($matches[1] ?? $matches[0]);
}
/**
* Remove all non-numeric characters from a string.
*
* @param string $value
* @return string
*/
public static function numbers($value)
{
return preg_replace('/[^0-9]/', '', $value);
}
/**
* Pad both sides of a string with another.
*
* @param string $value
* @param int $length
* @param string $pad
* @return string
*/
public static function padBoth($value, $length, $pad = ' ')
{
if (function_exists('mb_str_pad')) {
return mb_str_pad($value, $length, $pad, STR_PAD_BOTH);
}
$short = max(0, $length - mb_strlen($value));
$shortLeft = floor($short / 2);
$shortRight = ceil($short / 2);
return mb_substr(str_repeat($pad, $shortLeft), 0, $shortLeft).
$value.
mb_substr(str_repeat($pad, $shortRight), 0, $shortRight);
}
/**
* Pad the left side of a string with another.
*
* @param string $value
* @param int $length
* @param string $pad
* @return string
*/
public static function padLeft($value, $length, $pad = ' ')
{
if (function_exists('mb_str_pad')) {
return mb_str_pad($value, $length, $pad, STR_PAD_LEFT);
}
$short = max(0, $length - mb_strlen($value));
return mb_substr(str_repeat($pad, $short), 0, $short).$value;
}
/**
* Pad the right side of a string with another.
*
* @param string $value
* @param int $length
* @param string $pad
* @return string
*/
public static function padRight($value, $length, $pad = ' ')
{
if (function_exists('mb_str_pad')) {
return mb_str_pad($value, $length, $pad, STR_PAD_RIGHT);
}
$short = max(0, $length - mb_strlen($value));
return $value.mb_substr(str_repeat($pad, $short), 0, $short);
}
/**
* Parse a Class[@]method style callback into class and method.
*
* @param string $callback
* @param string|null $default
* @return array<int, string|null>
*/
public static function parseCallback($callback, $default = null)
{
if (static::contains($callback, "@anonymous\0")) {
if (static::substrCount($callback, '@') > 1) {
return [
static::beforeLast($callback, '@'),
static::afterLast($callback, '@'),
];
}
return [$callback, $default];
}
return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default];
}
/**
* Get the plural form of an English word.
*
* @param string $value
* @param int|array|\Countable $count
* @return string
*/
public static function plural($value, $count = 2)
{
return Pluralizer::plural($value, $count);
}
/**
* Pluralize the last word of an English, studly caps case string.
*
* @param string $value
* @param int|array|\Countable $count
* @return string
*/
public static function pluralStudly($value, $count = 2)
{
$parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
$lastWord = array_pop($parts);
return implode('', $parts).self::plural($lastWord, $count);
}