Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Str.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use Closure;
6 use Illuminate\Support\Traits\Macroable;
7 use League\CommonMark\Environment\Environment;
8 use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
9 use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension;
10 use League\CommonMark\GithubFlavoredMarkdownConverter;
11 use League\CommonMark\MarkdownConverter;
12 use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
13 use Ramsey\Uuid\Exception\InvalidUuidStringException;
14 use Ramsey\Uuid\Generator\CombGenerator;
15 use Ramsey\Uuid\Rfc4122\FieldsInterface;
16 use Ramsey\Uuid\Uuid;
17 use Ramsey\Uuid\UuidFactory;
18 use Symfony\Component\Uid\Ulid;
19 use Throwable;
20 use Traversable;
21 use voku\helper\ASCII;
22
23 class Str
24 {
25 use Macroable;
26
27 /**
28 * The list of characters that are considered "invisible" in strings.
29 *
30 * @var string
31 */
32 const INVISIBLE_CHARACTERS = '\x{0009}\x{0020}\x{00A0}\x{00AD}\x{034F}\x{061C}\x{115F}\x{1160}\x{17B4}\x{17B5}\x{180E}\x{2000}\x{2001}\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}\x{200A}\x{200B}\x{200C}\x{200D}\x{200E}\x{200F}\x{202F}\x{205F}\x{2060}\x{2061}\x{2062}\x{2063}\x{2064}\x{2065}\x{206A}\x{206B}\x{206C}\x{206D}\x{206E}\x{206F}\x{3000}\x{2800}\x{3164}\x{FEFF}\x{FFA0}\x{1D159}\x{1D173}\x{1D174}\x{1D175}\x{1D176}\x{1D177}\x{1D178}\x{1D179}\x{1D17A}\x{E0020}';
33
34 /**
35 * The cache of snake-cased words.
36 *
37 * @var array<string, string>
38 */
39 protected static $snakeCache = [];
40
41 /**
42 * The cache of camel-cased words.
43 *
44 * @var array<string, string>
45 */
46 protected static $camelCache = [];
47
48 /**
49 * The cache of studly-cased words.
50 *
51 * @var array<string, string>
52 */
53 protected static $studlyCache = [];
54
55 /**
56 * The callback that should be used to generate UUIDs.
57 *
58 * @var (callable(): \Ramsey\Uuid\UuidInterface)|null
59 */
60 protected static $uuidFactory;
61
62 /**
63 * The callback that should be used to generate ULIDs.
64 *
65 * @var (callable(): \Symfony\Component\Uid\Ulid)|null
66 */
67 protected static $ulidFactory;
68
69 /**
70 * The callback that should be used to generate random strings.
71 *
72 * @var (callable(int): string)|null
73 */
74 protected static $randomStringFactory;
75
76 /**
77 * Get a new stringable object from the given string.
78 *
79 * @param string $string
80 * @return \Illuminate\Support\Stringable
81 */
82 public static function of($string)
83 {
84 return new Stringable($string);
85 }
86
87 /**
88 * Return the remainder of a string after the first occurrence of a given value.
89 *
90 * @param string $subject
91 * @param string $search
92 * @return string
93 */
94 public static function after($subject, $search)
95 {
96 return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0];
97 }
98
99 /**
100 * Return the remainder of a string after the last occurrence of a given value.
101 *
102 * @param string $subject
103 * @param string $search
104 * @return string
105 */
106 public static function afterLast($subject, $search)
107 {
108 if ($search === '') {
109 return $subject;
110 }
111
112 $position = mb_strrpos($subject, $search);
113
114 if ($position === false) {
115 return $subject;
116 }
117
118 return static::substr($subject, $position + static::length($search));
119 }
120
121 /**
122 * Transliterate a UTF-8 value to ASCII.
123 *
124 * @param string $value
125 * @param string $language
126 * @return string
127 */
128 public static function ascii($value, $language = 'en')
129 {
130 return ASCII::to_ascii((string) $value, $language, replace_single_chars_only: false);
131 }
132
133 /**
134 * Transliterate a string to its closest ASCII representation.
135 *
136 * @param string $string
137 * @param string|null $unknown
138 * @param bool|null $strict
139 * @return string
140 */
141 public static function transliterate($string, $unknown = '?', $strict = false)
142 {
143 return ASCII::to_transliterate($string, $unknown, $strict);
144 }
145
146 /**
147 * Get the portion of a string before the first occurrence of a given value.
148 *
149 * @param string $subject
150 * @param string $search
151 * @return string
152 */
153 public static function before($subject, $search)
154 {
155 if ($search === '') {
156 return $subject;
157 }
158
159 $result = strstr($subject, (string) $search, true);
160
161 return $result === false ? $subject : $result;
162 }
163
164 /**
165 * Get the portion of a string before the last occurrence of a given value.
166 *
167 * @param string $subject
168 * @param string $search
169 * @return string
170 */
171 public static function beforeLast($subject, $search)
172 {
173 if ($search === '') {
174 return $subject;
175 }
176
177 $pos = mb_strrpos($subject, $search);
178
179 if ($pos === false) {
180 return $subject;
181 }
182
183 return static::substr($subject, 0, $pos);
184 }
185
186 /**
187 * Get the portion of a string between two given values.
188 *
189 * @param string $subject
190 * @param string $from
191 * @param string $to
192 * @return string
193 */
194 public static function between($subject, $from, $to)
195 {
196 if ($from === '' || $to === '') {
197 return $subject;
198 }
199
200 return static::beforeLast(static::after($subject, $from), $to);
201 }
202
203 /**
204 * Get the smallest possible portion of a string between two given values.
205 *
206 * @param string $subject
207 * @param string $from
208 * @param string $to
209 * @return string
210 */
211 public static function betweenFirst($subject, $from, $to)
212 {
213 if ($from === '' || $to === '') {
214 return $subject;
215 }
216
217 return static::before(static::after($subject, $from), $to);
218 }
219
220 /**
221 * Convert a value to camel case.
222 *
223 * @param string $value
224 * @return ($value is '' ? '' : string)
225 */
226 public static function camel($value)
227 {
228 if (isset(static::$camelCache[$value])) {
229 return static::$camelCache[$value];
230 }
231
232 return static::$camelCache[$value] = lcfirst(static::studly($value));
233 }
234
235 /**
236 * Get the character at the specified index.
237 *
238 * @param string $subject
239 * @param int $index
240 * @return string|false
241 */
242 public static function charAt($subject, $index)
243 {
244 $length = mb_strlen($subject);
245
246 if ($index < 0 ? $index < -$length : $index > $length - 1) {
247 return false;
248 }
249
250 return mb_substr($subject, $index, 1);
251 }
252
253 /**
254 * Remove the given string(s) if it exists at the start of the haystack.
255 *
256 * @param string $subject
257 * @param string|string[] $needle
258 * @return string
259 */
260 public static function chopStart($subject, $needle)
261 {
262 foreach ((array) $needle as $n) {
263 if ($n !== '' && str_starts_with($subject, $n)) {
264 return mb_substr($subject, mb_strlen($n));
265 }
266 }
267
268 return $subject;
269 }
270
271 /**
272 * Remove the given string(s) if it exists at the end of the haystack.
273 *
274 * @param string $subject
275 * @param string|string[] $needle
276 * @return string
277 */
278 public static function chopEnd($subject, $needle)
279 {
280 foreach ((array) $needle as $n) {
281 if ($n !== '' && str_ends_with($subject, $n)) {
282 return mb_substr($subject, 0, -mb_strlen($n));
283 }
284 }
285
286 return $subject;
287 }
288
289 /**
290 * Determine if a given string contains a given substring.
291 *
292 * @param string $haystack
293 * @param string|iterable<string> $needles
294 * @param bool $ignoreCase
295 * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
296 */
297 public static function contains($haystack, $needles, $ignoreCase = false)
298 {
299 if (is_null($haystack)) {
300 return false;
301 }
302
303 if ($ignoreCase) {
304 $haystack = mb_strtolower($haystack);
305 }
306
307 if (! is_iterable($needles)) {
308 $needles = (array) $needles;
309 }
310
311 foreach ($needles as $needle) {
312 if ($ignoreCase) {
313 $needle = mb_strtolower($needle);
314 }
315
316 if ($needle !== '' && str_contains($haystack, $needle)) {
317 return true;
318 }
319 }
320
321 return false;
322 }
323
324 /**
325 * Determine if a given string contains all array values.
326 *
327 * @param string $haystack
328 * @param iterable<string> $needles
329 * @param bool $ignoreCase
330 * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
331 */
332 public static function containsAll($haystack, $needles, $ignoreCase = false)
333 {
334 foreach ($needles as $needle) {
335 if (! static::contains($haystack, $needle, $ignoreCase)) {
336 return false;
337 }
338 }
339
340 return true;
341 }
342
343 /**
344 * Determine if a given string doesn't contain a given substring.
345 *
346 * @param string $haystack
347 * @param string|iterable<string> $needles
348 * @param bool $ignoreCase
349 * @return ($needles is array{} ? true : ($haystack is non-empty-string ? bool : true))
350 */
351 public static function doesntContain($haystack, $needles, $ignoreCase = false)
352 {
353 return ! static::contains($haystack, $needles, $ignoreCase);
354 }
355
356 /**
357 * Convert the case of a string.
358 *
359 * @param string $string
360 * @param MB_CASE_UPPER|MB_CASE_LOWER|MB_CASE_TITLE|MB_CASE_FOLD|MB_CASE_UPPER_SIMPLE|MB_CASE_LOWER_SIMPLE|MB_CASE_TITLE_SIMPLE|MB_CASE_FOLD_SIMPLE $mode
361 * @param string|null $encoding
362 * @return ($string is '' ? '' : string)
363 */
364 public static function convertCase(string $string, int $mode = MB_CASE_FOLD, ?string $encoding = 'UTF-8')
365 {
366 return mb_convert_case($string, $mode, $encoding);
367 }
368
369 /**
370 * Replace consecutive instances of a given character with a single character in the given string.
371 *
372 * @param string $string
373 * @param array<string>|string $characters
374 * @return ($string is '' ? '' : string)
375 */
376 public static function deduplicate(string $string, array|string $characters = ' ')
377 {
378 if (is_string($characters)) {
379 return preg_replace('/'.preg_quote($characters, '/').'+/u', $characters, $string);
380 }
381
382 return array_reduce(
383 $characters,
384 fn ($carry, $character) => preg_replace('/'.preg_quote($character, '/').'+/u', $character, $carry),
385 $string
386 );
387 }
388
389 /**
390 * Determine if a given string ends with a given substring.
391 *
392 * @param string $haystack
393 * @param string|iterable<string> $needles
394 * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
395 */
396 public static function endsWith($haystack, $needles)
397 {
398 if (is_null($haystack)) {
399 return false;
400 }
401
402 if (! is_iterable($needles)) {
403 $needles = (array) $needles;
404 }
405
406 foreach ($needles as $needle) {
407 if ((string) $needle !== '' && str_ends_with($haystack, $needle)) {
408 return true;
409 }
410 }
411
412 return false;
413 }
414
415 /**
416 * Determine if a given string doesn't end with a given substring.
417 *
418 * @param string $haystack
419 * @param string|iterable<string> $needles
420 * @return ($needles is array{} ? true : ($haystack is non-empty-string ? bool : true))
421 */
422 public static function doesntEndWith($haystack, $needles)
423 {
424 return ! static::endsWith($haystack, $needles);
425 }
426
427 /**
428 * Extracts an excerpt from text that matches the first instance of a phrase.
429 *
430 * @param string $text
431 * @param string $phrase
432 * @param array{radius?: int|float, omission?: string} $options
433 * @return string|null
434 */
435 public static function excerpt($text, $phrase = '', $options = [])
436 {
437 $radius = $options['radius'] ?? 100;
438 $omission = $options['omission'] ?? '...';
439
440 preg_match('/^(.*?)('.preg_quote((string) $phrase, '/').')(.*)$/iu', (string) $text, $matches);
441
442 if (empty($matches)) {
443 return null;
444 }
445
446 $start = ltrim($matches[1]);
447
448 $start = Str::of(mb_substr($start, max(mb_strlen($start, 'UTF-8') - $radius, 0), $radius, 'UTF-8'))->ltrim()->unless(
449 fn ($startWithRadius) => $startWithRadius->exactly($start),
450 fn ($startWithRadius) => $startWithRadius->prepend($omission),
451 );
452
453 $end = rtrim($matches[3]);
454
455 $end = Str::of(mb_substr($end, 0, $radius, 'UTF-8'))->rtrim()->unless(
456 fn ($endWithRadius) => $endWithRadius->exactly($end),
457 fn ($endWithRadius) => $endWithRadius->append($omission),
458 );
459
460 return $start->append($matches[2], $end)->toString();
461 }
462
463 /**
464 * Cap a string with a single instance of a given value.
465 *
466 * @param string $value
467 * @param string $cap
468 * @return ($value is '' ? ($cap is '' ? '' : non-empty-string) : non-empty-string)
469 */
470 public static function finish($value, $cap)
471 {
472 $quoted = preg_quote($cap, '/');
473
474 return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap;
475 }
476
477 /**
478 * Wrap the string with the given strings.
479 *
480 * @param string $value
481 * @param string $before
482 * @param string|null $after
483 * @return ($value is '' ? ($before is '' ? ($after is '' ? '' : ($after is null ? '' : non-empty-string)) : non-empty-string) : non-empty-string)
484 */
485 public static function wrap($value, $before, $after = null)
486 {
487 return $before.$value.($after ?? $before);
488 }
489
490 /**
491 * Unwrap the string with the given strings.
492 *
493 * @param string $value
494 * @param string $before
495 * @param string|null $after
496 * @return string
497 */
498 public static function unwrap($value, $before, $after = null)
499 {
500 if (static::startsWith($value, $before)) {
501 $value = static::substr($value, static::length($before));
502 }
503
504 if (static::endsWith($value, $after ??= $before)) {
505 $value = static::substr($value, 0, -static::length($after));
506 }
507
508 return $value;
509 }
510
511 /**
512 * Determine if a given string matches a given pattern.
513 *
514 * @param string|iterable<string> $pattern
515 * @param string $value
516 * @param bool $ignoreCase
517 * @return bool
518 */
519 public static function is($pattern, $value, $ignoreCase = false)
520 {
521 $value = (string) $value;
522
523 if (! is_iterable($pattern)) {
524 $pattern = [$pattern];
525 }
526
527 foreach ($pattern as $pattern) {
528 $pattern = (string) $pattern;
529
530 // If the given value is an exact match we can of course return true right
531 // from the beginning. Otherwise, we will translate asterisks and do an
532 // actual pattern match against the two strings to see if they match.
533 if ($pattern === '*' || $pattern === $value) {
534 return true;
535 }
536
537 if ($ignoreCase && mb_strtolower($pattern) === mb_strtolower($value)) {
538 return true;
539 }
540
541 $pattern = preg_quote($pattern, '#');
542
543 // Asterisks are translated into zero-or-more regular expression wildcards
544 // to make it convenient to check if the strings starts with the given
545 // pattern such as "library/*", making any string check convenient.
546 $pattern = str_replace('\*', '.*', $pattern);
547
548 if (preg_match('#^'.$pattern.'\z#'.($ignoreCase ? 'isu' : 'su'), $value) === 1) {
549 return true;
550 }
551 }
552
553 return false;
554 }
555
556 /**
557 * Determine if a given string is 7 bit ASCII.
558 *
559 * @param string $value
560 * @return bool
561 */
562 public static function isAscii($value)
563 {
564 return ASCII::is_ascii((string) $value);
565 }
566
567 /**
568 * Determine if a given value is valid JSON.
569 *
570 * @param mixed $value
571 * @return bool
572 *
573 * @phpstan-assert-if-true =non-empty-string $value
574 */
575 public static function isJson($value)
576 {
577 if (! is_string($value)) {
578 return false;
579 }
580
581 return json_validate($value, 512);
582 }
583
584 /**
585 * Determine if a given value is a valid URL.
586 *
587 * @param mixed $value
588 * @param string[] $protocols
589 * @return bool
590 *
591 * @phpstan-assert-if-true =non-empty-string $value
592 */
593 public static function isUrl($value, array $protocols = [])
594 {
595 if (! is_string($value)) {
596 return false;
597 }
598
599 $protocolList = empty($protocols)
600 ? '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'
601 : implode('|', $protocols);
602
603 /*
604 * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (5.0.7).
605 *
606 * (c) Fabien Potencier <[email protected]> http://symfony.com
607 */
608 $pattern = '~^
609 (LARAVEL_PROTOCOLS):// # protocol
610 (((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+)@)? # basic auth
611 (
612 (?:
613 (?:
614 (?:[\pL\pN\pS\pM\-\_]++\.)+
615 (?:
616 (?:xn--[a-z0-9-]++) # punycode in tld
617 |
618 (?:[\pL\pN\pM]++) # no punycode in tld
619 )
620 ) # a multi-level domain name
621 |
622 [a-z0-9\-\_]++ # a single-level domain name
623 )\.?
624 | # or
625 \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address
626 | # or
627 \[
628 (?:(?:(?:(?:(?:(?:(?:[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})))?::))))
629 \] # an IPv6 address
630 )
631 (:[0-9]+)? # a port (optional)
632 (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})* )* # a path
633 (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a query (optional)
634 (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a fragment (optional)
635 $~ixu';
636
637 return preg_match(str_replace('LARAVEL_PROTOCOLS', $protocolList, $pattern), $value) > 0;
638 }
639
640 /**
641 * Determine if a given value is a valid UUID.
642 *
643 * @param mixed $value
644 * @param int<0, 8>|'nil'|'max'|null $version
645 * @return bool
646 *
647 * @phpstan-assert-if-true =non-empty-string $value
648 */
649 public static function isUuid($value, $version = null)
650 {
651 if (! is_string($value)) {
652 return false;
653 }
654
655 if ($version === null) {
656 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;
657 }
658
659 $factory = new UuidFactory;
660
661 try {
662 $factoryUuid = $factory->fromString($value);
663 } catch (InvalidUuidStringException) {
664 return false;
665 }
666
667 $fields = $factoryUuid->getFields();
668
669 if (! ($fields instanceof FieldsInterface)) {
670 return false;
671 }
672
673 if ($version === 0 || $version === 'nil') {
674 return $fields->isNil();
675 }
676
677 if ($version === 'max') {
678 return $fields->isMax();
679 }
680
681 return $fields->getVersion() === $version;
682 }
683
684 /**
685 * Determine if a given value is a valid ULID.
686 *
687 * @param mixed $value
688 * @return bool
689 *
690 * @phpstan-assert-if-true =non-empty-string $value
691 */
692 public static function isUlid($value)
693 {
694 if (! is_string($value)) {
695 return false;
696 }
697
698 return Ulid::isValid($value);
699 }
700
701 /**
702 * Convert a string to kebab case.
703 *
704 * @param string $value
705 * @return ($value is '' ? '' : string)
706 */
707 public static function kebab($value)
708 {
709 return static::snake($value, '-');
710 }
711
712 /**
713 * Return the length of the given string.
714 *
715 * @param string $value
716 * @param string|null $encoding
717 * @return non-negative-int
718 */
719 public static function length($value, $encoding = null)
720 {
721 return mb_strlen($value, $encoding);
722 }
723
724 /**
725 * Limit the number of characters in a string.
726 *
727 * @param string $value
728 * @param int $limit
729 * @param string $end
730 * @param bool $preserveWords
731 * @return string
732 */
733 public static function limit($value, $limit = 100, $end = '...', $preserveWords = false)
734 {
735 if (mb_strwidth($value, 'UTF-8') <= $limit) {
736 return $value;
737 }
738
739 if (! $preserveWords) {
740 return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
741 }
742
743 $value = trim(preg_replace('/[\n\r]+/', ' ', strip_tags($value)));
744
745 $trimmed = rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8'));
746
747 if (mb_substr($value, $limit, 1, 'UTF-8') === ' ') {
748 return $trimmed.$end;
749 }
750
751 return preg_replace("/(.*)\s.*/", '$1', $trimmed).$end;
752 }
753
754 /**
755 * Convert the given string to lower-case.
756 *
757 * @param string $value
758 * @return ($value is '' ? '' : non-empty-string&lowercase-string)
759 */
760 public static function lower($value)
761 {
762 return mb_strtolower($value, 'UTF-8');
763 }
764
765 /**
766 * Limit the number of words in a string.
767 *
768 * @param string $value
769 * @param int $words
770 * @param string $end
771 * @return string
772 */
773 public static function words($value, $words = 100, $end = '...')
774 {
775 preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
776
777 if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
778 return $value;
779 }
780
781 return rtrim($matches[0]).$end;
782 }
783
784 /**
785 * Converts GitHub flavored Markdown into HTML.
786 *
787 * @param string $string
788 * @param array $options
789 * @param \League\CommonMark\Extension\ExtensionInterface[] $extensions
790 * @return ($string is '' ? '' : string)
791 */
792 public static function markdown($string, array $options = [], array $extensions = [])
793 {
794 $converter = new GithubFlavoredMarkdownConverter($options);
795
796 $environment = $converter->getEnvironment();
797
798 foreach ($extensions as $extension) {
799 $environment->addExtension($extension);
800 }
801
802 return (string) $converter->convert($string);
803 }
804
805 /**
806 * Converts inline Markdown into HTML.
807 *
808 * @param string $string
809 * @param array $options
810 * @param \League\CommonMark\Extension\ExtensionInterface[] $extensions
811 * @return ($string is '' ? '' : string)
812 */
813 public static function inlineMarkdown($string, array $options = [], array $extensions = [])
814 {
815 $environment = new Environment($options);
816
817 $environment->addExtension(new GithubFlavoredMarkdownExtension());
818 $environment->addExtension(new InlinesOnlyExtension());
819
820 foreach ($extensions as $extension) {
821 $environment->addExtension($extension);
822 }
823
824 $converter = new MarkdownConverter($environment);
825
826 return (string) $converter->convert($string);
827 }
828
829 /**
830 * Masks a portion of a string with a repeated character.
831 *
832 * @param string $string
833 * @param string $character
834 * @param int $index
835 * @param int|null $length
836 * @param string $encoding
837 * @return string
838 */
839 public static function mask($string, $character, $index, $length = null, $encoding = 'UTF-8')
840 {
841 if ($character === '') {
842 return $string;
843 }
844
845 $segment = mb_substr($string, $index, $length, $encoding);
846
847 if ($segment === '') {
848 return $string;
849 }
850
851 $strlen = mb_strlen($string, $encoding);
852 $startIndex = $index;
853
854 if ($index < 0) {
855 $startIndex = $index < -$strlen ? 0 : $strlen + $index;
856 }
857
858 $start = mb_substr($string, 0, $startIndex, $encoding);
859 $segmentLen = mb_strlen($segment, $encoding);
860 $end = mb_substr($string, $startIndex + $segmentLen);
861
862 return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end;
863 }
864
865 /**
866 * Get the string matching the given pattern.
867 *
868 * @param string $pattern
869 * @param string $subject
870 * @return string
871 */
872 public static function match($pattern, $subject)
873 {
874 preg_match($pattern, $subject, $matches);
875
876 if (! $matches) {
877 return '';
878 }
879
880 return $matches[1] ?? $matches[0];
881 }
882
883 /**
884 * Determine if a given string matches a given pattern.
885 *
886 * @param string|iterable<string> $pattern
887 * @param string $value
888 * @return ($pattern is array{} ? false : bool)
889 */
890 public static function isMatch($pattern, $value)
891 {
892 $value = (string) $value;
893
894 if (! is_iterable($pattern)) {
895 $pattern = [$pattern];
896 }
897
898 foreach ($pattern as $pattern) {
899 $pattern = (string) $pattern;
900
901 if (preg_match($pattern, $value) === 1) {
902 return true;
903 }
904 }
905
906 return false;
907 }
908
909 /**
910 * Get the string matching the given pattern.
911 *
912 * @param string $pattern
913 * @param string $subject
914 * @return \Illuminate\Support\Collection
915 */
916 public static function matchAll($pattern, $subject)
917 {
918 preg_match_all($pattern, $subject, $matches);
919
920 if (empty($matches[0])) {
921 return new Collection;
922 }
923
924 return new Collection($matches[1] ?? $matches[0]);
925 }
926
927 /**
928 * Remove all non-numeric characters from a string.
929 *
930 * @param string $value
931 * @return string
932 */
933 public static function numbers($value)
934 {
935 return preg_replace('/[^0-9]/', '', $value);
936 }
937
938 /**
939 * Pad both sides of a string with another.
940 *
941 * @param string $value
942 * @param int $length
943 * @param string $pad
944 * @return string
945 */
946 public static function padBoth($value, $length, $pad = ' ')
947 {
948 return mb_str_pad($value, $length, $pad, STR_PAD_BOTH);
949 }
950
951 /**
952 * Pad the left side of a string with another.
953 *
954 * @param string $value
955 * @param int $length
956 * @param string $pad
957 * @return string
958 */
959 public static function padLeft($value, $length, $pad = ' ')
960 {
961 return mb_str_pad($value, $length, $pad, STR_PAD_LEFT);
962 }
963
964 /**
965 * Pad the right side of a string with another.
966 *
967 * @param string $value
968 * @param int $length
969 * @param string $pad
970 * @return string
971 */
972 public static function padRight($value, $length, $pad = ' ')
973 {
974 return mb_str_pad($value, $length, $pad, STR_PAD_RIGHT);
975 }
976
977 /**
978 * Parse a Class[@]method style callback into class and method.
979 *
980 * @param string $callback
981 * @param string|null $default
982 * @return array<int, string|null>
983 */
984 public static function parseCallback($callback, $default = null)
985 {
986 if (static::contains($callback, "@anonymous\0")) {
987 if (static::substrCount($callback, '@') > 1) {
988 return [
989 static::beforeLast($callback, '@'),
990 static::afterLast($callback, '@'),
991 ];
992 }
993
994 return [$callback, $default];
995 }
996
997 return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default];
998 }
999
1000 /**
1001 * Get the plural form of an English word.
1002 *
1003 * @param string $value
1004 * @param int|array|\Countable $count
1005 * @param bool $prependCount
1006 * @return string
1007 */
1008 public static function plural($value, $count = 2, $prependCount = false)
1009 {
1010 if (is_countable($count)) {
1011 $count = count($count);
1012 }
1013
1014 return ($prependCount ? Number::format($count).' ' : '').Pluralizer::plural($value, $count);
1015 }
1016
1017 /**
1018 * Pluralize the last word of an English, studly caps case string.
1019 *
1020 * @param string $value
1021 * @param int|array|\Countable $count
1022 * @return string
1023 */
1024 public static function pluralStudly($value, $count = 2)
1025 {
1026 $parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
1027
1028 $lastWord = array_pop($parts);
1029
1030 return implode('', $parts).self::plural($lastWord, $count);
1031 }
1032
1033 /**
1034 * Pluralize the last word of an English, Pascal caps case string.
1035 *
1036 * @param string $value
1037 * @param int|array|\Countable $count
1038 * @return string
1039 */
1040 public static function pluralPascal($value, $count = 2)
1041 {
1042 return static::pluralStudly($value, $count);
1043 }
1044
1045 /**
1046 * Generate a random, secure password.
1047 *
1048 * @param int $length
1049 * @param bool $letters
1050 * @param bool $numbers
1051 * @param bool $symbols
1052 * @param bool $spaces
1053 * @return ($letters is false ? ($numbers is true ? ($symbols is false ? ($spaces is false ? numeric-string : string) : string) : string) : string)
1054 */
1055 public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false)
1056 {
1057 $password = new Collection();
1058
1059 $options = (new Collection([
1060 'letters' => $letters === true ? [
1061 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
1062 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
1063 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
1064 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
1065 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
1066 ] : null,
1067 'numbers' => $numbers === true ? [
1068 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1069 ] : null,
1070 'symbols' => $symbols === true ? [
1071 '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-',
1072 '_', '.', ',', '<', '>', '?', '/', '\\', '{', '}', '[',
1073 ']', '|', ':', ';',
1074 ] : null,
1075 'spaces' => $spaces === true ? [' '] : null,
1076 ]))
1077 ->filter()
1078 ->each(fn ($c) => $password->push($c[random_int(0, count($c) - 1)]))
1079 ->flatten();
1080
1081 $length = $length - $password->count();
1082
1083 return $password->merge($options->pipe(
1084 fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)])
1085 ))->shuffle()->implode('');
1086 }
1087
1088 /**
1089 * Find the multi-byte safe position of the first occurrence of a given substring in a string.
1090 *
1091 * @param string $haystack
1092 * @param string $needle
1093 * @param int $offset
1094 * @param string|null $encoding
1095 * @return ($haystack is '' ? false : ($needle is '' ? false : int|false))
1096 */
1097 public static function position($haystack, $needle, $offset = 0, $encoding = null)
1098 {
1099 return mb_strpos($haystack, (string) $needle, $offset, $encoding);
1100 }
1101
1102 /**
1103 * Generate a more truly "random" alpha-numeric string.
1104 *
1105 * @param int $length
1106 * @return string
1107 */
1108 public static function random($length = 16)
1109 {
1110 return (static::$randomStringFactory ?? function ($length) {
1111 $string = '';
1112
1113 while (($len = strlen($string)) < $length) {
1114 $size = $length - $len;
1115
1116 $bytesSize = (int) ceil($size / 3) * 3;
1117
1118 $bytes = random_bytes($bytesSize);
1119
1120 $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
1121 }
1122
1123 return $string;
1124 })($length);
1125 }
1126
1127 /**
1128 * Set the callable that will be used to generate random strings.
1129 *
1130 * @param (callable(int): string)|null $factory
1131 * @return void
1132 */
1133 public static function createRandomStringsUsing(?callable $factory = null)
1134 {
1135 static::$randomStringFactory = $factory;
1136 }
1137
1138 /**
1139 * Set the sequence that will be used to generate random strings.
1140 *
1141 * @param string[] $sequence
1142 * @param (callable(int): string)|null $whenMissing
1143 * @return void
1144 */
1145 public static function createRandomStringsUsingSequence(array $sequence, $whenMissing = null)
1146 {
1147 $next = 0;
1148
1149 $whenMissing ??= function ($length) use (&$next) {
1150 $factoryCache = static::$randomStringFactory;
1151
1152 static::$randomStringFactory = null;
1153
1154 $randomString = static::random($length);
1155
1156 static::$randomStringFactory = $factoryCache;
1157
1158 $next++;
1159
1160 return $randomString;
1161 };
1162
1163 static::createRandomStringsUsing(function ($length) use (&$next, $sequence, $whenMissing) {
1164 if (array_key_exists($next, $sequence)) {
1165 return $sequence[$next++];
1166 }
1167
1168 return $whenMissing($length);
1169 });
1170 }
1171
1172 /**
1173 * Indicate that random strings should be created normally and not using a custom factory.
1174 *
1175 * @return void
1176 */
1177 public static function createRandomStringsNormally()
1178 {
1179 static::$randomStringFactory = null;
1180 }
1181
1182 /**
1183 * Repeat the given string.
1184 *
1185 * @param string $string
1186 * @param int $times
1187 * @return string
1188 */
1189 public static function repeat(string $string, int $times)
1190 {
1191 return str_repeat($string, $times);
1192 }
1193
1194 /**
1195 * Replace a given value in the string sequentially with an array.
1196 *
1197 * @param string $search
1198 * @param iterable<string> $replace
1199 * @param string $subject
1200 * @return string
1201 */
1202 public static function replaceArray($search, $replace, $subject)
1203 {
1204 if ($replace instanceof Traversable) {
1205 $replace = Arr::from($replace);
1206 }
1207
1208 $segments = explode($search, $subject);
1209
1210 $result = array_shift($segments);
1211
1212 foreach ($segments as $segment) {
1213 $result .= self::toStringOr(array_shift($replace) ?? $search, $search).$segment;
1214 }
1215
1216 return $result;
1217 }
1218
1219 /**
1220 * Convert the given value to a string or return the given fallback on failure.
1221 *
1222 * @param mixed $value
1223 * @param string $fallback
1224 * @return string
1225 */
1226 private static function toStringOr($value, $fallback)
1227 {
1228 try {
1229 return (string) $value;
1230 } catch (Throwable $e) {
1231 return $fallback;
1232 }
1233 }
1234
1235 /**
1236 * Replace the given value in the given string.
1237 *
1238 * @param string|iterable<string> $search
1239 * @param string|iterable<string> $replace
1240 * @param string|iterable<string> $subject
1241 * @param bool $caseSensitive
1242 * @return ($subject is string ? string : string[])
1243 */
1244 public static function replace($search, $replace, $subject, $caseSensitive = true)
1245 {
1246 if ($search instanceof Traversable) {
1247 $search = Arr::from($search);
1248 }
1249
1250 if ($replace instanceof Traversable) {
1251 $replace = Arr::from($replace);
1252 }
1253
1254 if ($subject instanceof Traversable) {
1255 $subject = Arr::from($subject);
1256 }
1257
1258 return $caseSensitive
1259 ? str_replace($search, $replace, $subject)
1260 : str_ireplace($search, $replace, $subject);
1261 }
1262
1263 /**
1264 * Replace the first occurrence of a given value in the string.
1265 *
1266 * @param string $search
1267 * @param string $replace
1268 * @param string $subject
1269 * @return string
1270 */
1271 public static function replaceFirst($search, $replace, $subject)
1272 {
1273 $search = (string) $search;
1274
1275 if ($search === '') {
1276 return $subject;
1277 }
1278
1279 $position = strpos($subject, $search);
1280
1281 if ($position !== false) {
1282 return substr_replace($subject, $replace, $position, strlen($search));
1283 }
1284
1285 return $subject;
1286 }
1287
1288 /**
1289 * Replace the first occurrence of the given value if it appears at the start of the string.
1290 *
1291 * @param string $search
1292 * @param string $replace
1293 * @param string $subject
1294 * @return string
1295 */
1296 public static function replaceStart($search, $replace, $subject)
1297 {
1298 $search = (string) $search;
1299
1300 if ($search === '') {
1301 return $subject;
1302 }
1303
1304 if (static::startsWith($subject, $search)) {
1305 return static::replaceFirst($search, $replace, $subject);
1306 }
1307
1308 return $subject;
1309 }
1310
1311 /**
1312 * Replace the last occurrence of a given value in the string.
1313 *
1314 * @param string $search
1315 * @param string $replace
1316 * @param string $subject
1317 * @return string
1318 */
1319 public static function replaceLast($search, $replace, $subject)
1320 {
1321 $search = (string) $search;
1322
1323 if ($search === '') {
1324 return $subject;
1325 }
1326
1327 $position = strrpos($subject, $search);
1328
1329 if ($position !== false) {
1330 return substr_replace($subject, $replace, $position, strlen($search));
1331 }
1332
1333 return $subject;
1334 }
1335
1336 /**
1337 * Replace the last occurrence of a given value if it appears at the end of the string.
1338 *
1339 * @param string $search
1340 * @param string $replace
1341 * @param string $subject
1342 * @return string
1343 */
1344 public static function replaceEnd($search, $replace, $subject)
1345 {
1346 $search = (string) $search;
1347
1348 if ($search === '') {
1349 return $subject;
1350 }
1351
1352 if (static::endsWith($subject, $search)) {
1353 return static::replaceLast($search, $replace, $subject);
1354 }
1355
1356 return $subject;
1357 }
1358
1359 /**
1360 * Replace the patterns matching the given regular expression.
1361 *
1362 * @param string|string[] $pattern
1363 * @param (\Closure(array): string)|string[]|string $replace
1364 * @param string[]|string $subject
1365 * @param int $limit
1366 * @return ($subject is array ? string[]|null : string|null)
1367 */
1368 public static function replaceMatches($pattern, $replace, $subject, $limit = -1)
1369 {
1370 if ($replace instanceof Closure) {
1371 return preg_replace_callback($pattern, $replace, $subject, $limit);
1372 }
1373
1374 return preg_replace($pattern, $replace, $subject, $limit);
1375 }
1376
1377 /**
1378 * Remove any occurrence of the given string in the subject.
1379 *
1380 * @param string|iterable<string> $search
1381 * @param string|iterable<string> $subject
1382 * @param bool $caseSensitive
1383 * @return string
1384 */
1385 public static function remove($search, $subject, $caseSensitive = true)
1386 {
1387 if ($search instanceof Traversable) {
1388 $search = Arr::from($search);
1389 }
1390
1391 return $caseSensitive
1392 ? str_replace($search, '', $subject)
1393 : str_ireplace($search, '', $subject);
1394 }
1395
1396 /**
1397 * Reverse the given string.
1398 *
1399 * @param string $value
1400 * @return string
1401 */
1402 public static function reverse(string $value)
1403 {
1404 return implode(array_reverse(mb_str_split($value)));
1405 }
1406
1407 /**
1408 * Begin a string with a single instance of a given value.
1409 *
1410 * @param string $value
1411 * @param string $prefix
1412 * @return ($value is '' ? ($prefix is '' ? '' : non-empty-string): non-empty-string)
1413 */
1414 public static function start($value, $prefix)
1415 {
1416 $quoted = preg_quote($prefix, '/');
1417
1418 return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value);
1419 }
1420
1421 /**
1422 * Convert the given string to upper-case.
1423 *
1424 * @param string $value
1425 * @return ($value is '' ? '' : non-empty-string&uppercase-string)
1426 */
1427 public static function upper($value)
1428 {
1429 return mb_strtoupper($value, 'UTF-8');
1430 }
1431
1432 /**
1433 * Convert the given string to proper case.
1434 *
1435 * @param string $value
1436 * @return string
1437 */
1438 public static function title($value)
1439 {
1440 return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
1441 }
1442
1443 /**
1444 * Convert the given string to proper case for each word.
1445 *
1446 * @param string $value
1447 * @return string
1448 */
1449 public static function headline($value)
1450 {
1451 $parts = mb_split('\s+', $value);
1452
1453 $parts = count($parts) > 1
1454 ? array_map(static::title(...), $parts)
1455 : array_map(static::title(...), static::ucsplit(implode('_', $parts)));
1456
1457 $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts));
1458
1459 return implode(' ', array_filter(explode('_', $collapsed)));
1460 }
1461
1462 /**
1463 * Get the "initials" representing each word in the provided string, optionally capitalizing.
1464 *
1465 * @param string $value
1466 * @param bool $capitalize
1467 * @return string
1468 */
1469 public static function initials($value, $capitalize = false)
1470 {
1471 $parts = mb_split("\s+", $value);
1472
1473 $parts = array_map(fn ($part) => mb_substr($part, 0, 1), $parts);
1474
1475 $initials = implode('', $parts);
1476
1477 return $capitalize ? static::upper($initials) : $initials;
1478 }
1479
1480 /**
1481 * Convert the given string to APA-style title case.
1482 *
1483 * See: https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case
1484 *
1485 * @param string $value
1486 * @return string
1487 */
1488 public static function apa($value)
1489 {
1490 if (trim($value) === '') {
1491 return $value;
1492 }
1493
1494 $minorWords = [
1495 'and', 'as', 'but', 'for', 'if', 'nor', 'or', 'so', 'yet', 'a', 'an',
1496 'the', 'at', 'by', 'in', 'of', 'off', 'on', 'per', 'to', 'up', 'via',
1497 'et', 'ou', 'un', 'une', 'la', 'le', 'les', 'de', 'du', 'des', 'par', 'à',
1498 ];
1499
1500 $endPunctuation = ['.', '!', '?', ':', '—', ','];
1501
1502 $words = mb_split('\s+', $value);
1503 $wordCount = count($words);
1504
1505 for ($i = 0; $i < $wordCount; $i++) {
1506 $lowercaseWord = mb_strtolower($words[$i]);
1507
1508 if (str_contains($lowercaseWord, '-')) {
1509 $hyphenatedWords = explode('-', $lowercaseWord);
1510
1511 $hyphenatedWords = array_map(function ($part) use ($minorWords) {
1512 return (in_array($part, $minorWords) && mb_strlen($part) <= 3)
1513 ? $part
1514 : mb_strtoupper(mb_substr($part, 0, 1)).mb_substr($part, 1);
1515 }, $hyphenatedWords);
1516
1517 $words[$i] = implode('-', $hyphenatedWords);
1518 } else {
1519 if (in_array($lowercaseWord, $minorWords) &&
1520 mb_strlen($lowercaseWord) <= 3 &&
1521 ! ($i === 0 || in_array(mb_substr($words[$i - 1], -1), $endPunctuation))) {
1522 $words[$i] = $lowercaseWord;
1523 } else {
1524 $words[$i] = mb_strtoupper(mb_substr($lowercaseWord, 0, 1)).mb_substr($lowercaseWord, 1);
1525 }
1526 }
1527 }
1528
1529 return implode(' ', $words);
1530 }
1531
1532 /**
1533 * Get the singular form of an English word.
1534 *
1535 * @param string $value
1536 * @return string
1537 */
1538 public static function singular($value)
1539 {
1540 return Pluralizer::singular($value);
1541 }
1542
1543 /**
1544 * Generate a URL friendly "slug" from a given string.
1545 *
1546 * @param string $title
1547 * @param string $separator
1548 * @param string|null $language
1549 * @param array<string, string> $dictionary
1550 * @return string
1551 */
1552 public static function slug($title, $separator = '-', $language = 'en', $dictionary = ['@' => 'at'])
1553 {
1554 $title = $language ? static::ascii($title, $language) : $title;
1555
1556 // Convert all dashes/underscores into separator
1557 $flip = $separator === '-' ? '_' : '-';
1558
1559 $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
1560
1561 // Replace dictionary words
1562 foreach ($dictionary as $key => $value) {
1563 $dictionary[$key] = $separator.$value.$separator;
1564 }
1565
1566 $title = str_replace(array_keys($dictionary), array_values($dictionary), $title);
1567
1568 // Remove all characters that are not the separator, letters, numbers, or whitespace
1569 $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));
1570
1571 // Replace all separator characters and whitespace by a single separator
1572 $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
1573
1574 return trim($title, $separator);
1575 }
1576
1577 /**
1578 * Convert a string to snake case.
1579 *
1580 * @param string $value
1581 * @param string $delimiter
1582 * @return string
1583 */
1584 public static function snake($value, $delimiter = '_')
1585 {
1586 $key = $value;
1587
1588 if (isset(static::$snakeCache[$key][$delimiter])) {
1589 return static::$snakeCache[$key][$delimiter];
1590 }
1591
1592 if (! ctype_lower($value)) {
1593 $value = preg_replace('/\s+/u', '', ucwords($value));
1594
1595 $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value));
1596 }
1597
1598 return static::$snakeCache[$key][$delimiter] = $value;
1599 }
1600
1601 /**
1602 * Remove all whitespace from both ends of a string.
1603 *
1604 * @param string $value
1605 * @param string|null $charlist
1606 * @return string
1607 */
1608 public static function trim($value, $charlist = null)
1609 {
1610 if ($charlist === null) {
1611 $trimDefaultCharacters = " \n\r\t\v\0";
1612
1613 return preg_replace('~^[\s'.self::INVISIBLE_CHARACTERS.$trimDefaultCharacters.']+|[\s'.self::INVISIBLE_CHARACTERS.$trimDefaultCharacters.']+$~u', '', $value) ?? trim($value);
1614 }
1615
1616 return trim($value, $charlist);
1617 }
1618
1619 /**
1620 * Remove all whitespace from the beginning of a string.
1621 *
1622 * @param string $value
1623 * @param string|null $charlist
1624 * @return string
1625 */
1626 public static function ltrim($value, $charlist = null)
1627 {
1628 if ($charlist === null) {
1629 $ltrimDefaultCharacters = " \n\r\t\v\0";
1630
1631 return preg_replace('~^[\s'.self::INVISIBLE_CHARACTERS.$ltrimDefaultCharacters.']+~u', '', $value) ?? ltrim($value);
1632 }
1633
1634 return ltrim($value, $charlist);
1635 }
1636
1637 /**
1638 * Remove all whitespace from the end of a string.
1639 *
1640 * @param string $value
1641 * @param string|null $charlist
1642 * @return string
1643 */
1644 public static function rtrim($value, $charlist = null)
1645 {
1646 if ($charlist === null) {
1647 $rtrimDefaultCharacters = " \n\r\t\v\0";
1648
1649 return preg_replace('~[\s'.self::INVISIBLE_CHARACTERS.$rtrimDefaultCharacters.']+$~u', '', $value) ?? rtrim($value);
1650 }
1651
1652 return rtrim($value, $charlist);
1653 }
1654
1655 /**
1656 * Remove all "extra" blank space from the given string.
1657 *
1658 * @param string $value
1659 * @return string
1660 */
1661 public static function squish($value)
1662 {
1663 return preg_replace('~(\s|\x{3164}|\x{1160})+~u', ' ', static::trim($value));
1664 }
1665
1666 /**
1667 * Determine if a given string starts with a given substring.
1668 *
1669 * @param string $haystack
1670 * @param string|iterable<string> $needles
1671 * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
1672 *
1673 * @phpstan-assert-if-true =non-empty-string $haystack
1674 */
1675 public static function startsWith($haystack, $needles)
1676 {
1677 if (is_null($haystack)) {
1678 return false;
1679 }
1680
1681 if (! is_iterable($needles)) {
1682 $needles = [$needles];
1683 }
1684
1685 foreach ($needles as $needle) {
1686 if ((string) $needle !== '' && str_starts_with($haystack, $needle)) {
1687 return true;
1688 }
1689 }
1690
1691 return false;
1692 }
1693
1694 /**
1695 * Determine if a given string doesn't start with a given substring.
1696 *
1697 * @param string $haystack
1698 * @param string|iterable<string> $needles
1699 * @return ($needles is array{} ? true : ($haystack is non-empty-string ? bool : true))
1700 *
1701 * @phpstan-assert-if-false =non-empty-string $haystack
1702 */
1703 public static function doesntStartWith($haystack, $needles)
1704 {
1705 return ! static::startsWith($haystack, $needles);
1706 }
1707
1708 /**
1709 * Convert a value to studly caps case.
1710 *
1711 * @param string $value
1712 * @return ($value is '' ? '' : string)
1713 */
1714 public static function studly($value)
1715 {
1716 $key = $value;
1717
1718 if (isset(static::$studlyCache[$key])) {
1719 return static::$studlyCache[$key];
1720 }
1721
1722 $words = mb_split('\s+', static::replace(['-', '_'], ' ', $value));
1723
1724 $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words);
1725
1726 return static::$studlyCache[$key] = implode($studlyWords);
1727 }
1728
1729 /**
1730 * Convert a value to Pascal case.
1731 *
1732 * @param string $value
1733 * @return ($value is '' ? '' : string)
1734 */
1735 public static function pascal($value)
1736 {
1737 return static::studly($value);
1738 }
1739
1740 /**
1741 * Returns the portion of the string specified by the start and length parameters.
1742 *
1743 * @param string $string
1744 * @param int $start
1745 * @param int|null $length
1746 * @param string $encoding
1747 * @return string
1748 */
1749 public static function substr($string, $start, $length = null, $encoding = 'UTF-8')
1750 {
1751 return mb_substr($string, $start, $length, $encoding);
1752 }
1753
1754 /**
1755 * Returns the number of substring occurrences.
1756 *
1757 * @param string $haystack
1758 * @param string $needle
1759 * @param int $offset
1760 * @param int|null $length
1761 * @return int
1762 */
1763 public static function substrCount($haystack, $needle, $offset = 0, $length = null)
1764 {
1765 if (! is_null($length)) {
1766 return substr_count($haystack, $needle, $offset, $length);
1767 }
1768
1769 return substr_count($haystack, $needle, $offset);
1770 }
1771
1772 /**
1773 * Replace text within a portion of a string.
1774 *
1775 * @param string|string[] $string
1776 * @param string|string[] $replace
1777 * @param int|int[] $offset
1778 * @param int|int[]|null $length
1779 * @return string|string[]
1780 */
1781 public static function substrReplace($string, $replace, $offset = 0, $length = null)
1782 {
1783 if ($length === null) {
1784 $length = static::length($string);
1785 }
1786
1787 return mb_substr($string, 0, $offset)
1788 .$replace
1789 .mb_substr(mb_substr($string, $offset), $length);
1790 }
1791
1792 /**
1793 * Swap multiple keywords in a string with other keywords.
1794 *
1795 * @param array<string, string> $map
1796 * @param string $subject
1797 * @return string
1798 */
1799 public static function swap(array $map, $subject)
1800 {
1801 return strtr($subject, $map);
1802 }
1803
1804 /**
1805 * Take the first or last {$limit} characters of a string.
1806 *
1807 * @param string $string
1808 * @param int $limit
1809 * @return string
1810 */
1811 public static function take($string, int $limit): string
1812 {
1813 if ($limit < 0) {
1814 return static::substr($string, $limit);
1815 }
1816
1817 return static::substr($string, 0, $limit);
1818 }
1819
1820 /**
1821 * Convert the given string to Base64 encoding.
1822 *
1823 * @param string $string
1824 * @return ($string is '' ? '' : string)
1825 */
1826 public static function toBase64($string): string
1827 {
1828 return base64_encode($string);
1829 }
1830
1831 /**
1832 * Decode the given Base64 encoded string.
1833 *
1834 * @param string $string
1835 * @param bool $strict
1836 * @return ($strict is true ? ($string is '' ? '' : string|false) : ($string is '' ? '' : string))
1837 */
1838 public static function fromBase64($string, $strict = false)
1839 {
1840 return base64_decode($string, $strict);
1841 }
1842
1843 /**
1844 * Make a string's first character lowercase.
1845 *
1846 * @param string $string
1847 * @return ($string is '' ? '' : non-empty-string)
1848 */
1849 public static function lcfirst($string)
1850 {
1851 return static::lower(static::substr($string, 0, 1)).static::substr($string, 1);
1852 }
1853
1854 /**
1855 * Make a string's first character uppercase.
1856 *
1857 * @param string $string
1858 * @return ($string is '' ? '' : non-empty-string)
1859 */
1860 public static function ucfirst($string)
1861 {
1862 return static::upper(static::substr($string, 0, 1)).static::substr($string, 1);
1863 }
1864
1865 /**
1866 * Capitalize the first character of each word in a string.
1867 *
1868 * @param string $string
1869 * @param string $separators
1870 * @return ($string is '' ? '' : non-empty-string)
1871 */
1872 public static function ucwords($string, $separators = " \t\r\n\f\v")
1873 {
1874 $pattern = '/(^|['.preg_quote($separators, '/').'])(\p{Ll})/u';
1875
1876 return preg_replace_callback($pattern, function ($matches) {
1877 return $matches[1].mb_strtoupper($matches[2]);
1878 }, $string);
1879 }
1880
1881 /**
1882 * Split a string into pieces by uppercase characters.
1883 *
1884 * @param string $string
1885 * @return ($string is '' ? array{} : string[])
1886 */
1887 public static function ucsplit($string)
1888 {
1889 return preg_split('/(?=\p{Lu})/u', $string, -1, PREG_SPLIT_NO_EMPTY);
1890 }
1891
1892 /**
1893 * Get the number of words a string contains.
1894 *
1895 * @param string $string
1896 * @param string|null $characters
1897 * @return non-negative-int
1898 */
1899 public static function wordCount($string, $characters = null)
1900 {
1901 return str_word_count($string, 0, $characters);
1902 }
1903
1904 /**
1905 * Wrap a string to a given number of characters.
1906 *
1907 * @param string $string
1908 * @param int $characters
1909 * @param string $break
1910 * @param bool $cutLongWords
1911 * @return string
1912 */
1913 public static function wordWrap($string, $characters = 75, $break = "\n", $cutLongWords = false)
1914 {
1915 return wordwrap($string, $characters, $break, $cutLongWords);
1916 }
1917
1918 /**
1919 * Generate a UUID (version 4).
1920 *
1921 * @return \Ramsey\Uuid\UuidInterface
1922 */
1923 public static function uuid()
1924 {
1925 return static::$uuidFactory
1926 ? call_user_func(static::$uuidFactory)
1927 : Uuid::uuid4();
1928 }
1929
1930 /**
1931 * Generate a UUID (version 7).
1932 *
1933 * @param \DateTimeInterface|null $time
1934 * @return \Ramsey\Uuid\UuidInterface
1935 */
1936 public static function uuid7($time = null)
1937 {
1938 return static::$uuidFactory
1939 ? call_user_func(static::$uuidFactory)
1940 : Uuid::uuid7($time);
1941 }
1942
1943 /**
1944 * Generate a time-ordered UUID.
1945 *
1946 * @return \Ramsey\Uuid\UuidInterface
1947 */
1948 public static function orderedUuid()
1949 {
1950 if (static::$uuidFactory) {
1951 return call_user_func(static::$uuidFactory);
1952 }
1953
1954 $factory = new UuidFactory;
1955
1956 $factory->setRandomGenerator(new CombGenerator(
1957 $factory->getRandomGenerator(),
1958 $factory->getNumberConverter()
1959 ));
1960
1961 $factory->setCodec(new TimestampFirstCombCodec(
1962 $factory->getUuidBuilder()
1963 ));
1964
1965 return $factory->uuid4();
1966 }
1967
1968 /**
1969 * Set the callable that will be used to generate UUIDs.
1970 *
1971 * @param (callable(): \Ramsey\Uuid\UuidInterface)|null $factory
1972 * @return void
1973 */
1974 public static function createUuidsUsing(?callable $factory = null)
1975 {
1976 static::$uuidFactory = $factory;
1977 }
1978
1979 /**
1980 * Set the sequence that will be used to generate UUIDs.
1981 *
1982 * @param \Ramsey\Uuid\UuidInterface[] $sequence
1983 * @param (callable(): \Ramsey\Uuid\UuidInterface)|null $whenMissing
1984 * @return void
1985 */
1986 public static function createUuidsUsingSequence(array $sequence, $whenMissing = null)
1987 {
1988 $next = 0;
1989
1990 $whenMissing ??= function () use (&$next) {
1991 $factoryCache = static::$uuidFactory;
1992
1993 static::$uuidFactory = null;
1994
1995 $uuid = static::uuid();
1996
1997 static::$uuidFactory = $factoryCache;
1998
1999 $next++;
2000
2001 return $uuid;
2002 };
2003
2004 static::createUuidsUsing(function () use (&$next, $sequence, $whenMissing) {
2005 if (array_key_exists($next, $sequence)) {
2006 return $sequence[$next++];
2007 }
2008
2009 return $whenMissing();
2010 });
2011 }
2012
2013 /**
2014 * Always return the same UUID when generating new UUIDs.
2015 *
2016 * @param (\Closure(\Ramsey\Uuid\UuidInterface): mixed)|null $callback
2017 * @return \Ramsey\Uuid\UuidInterface
2018 */
2019 public static function freezeUuids(?Closure $callback = null)
2020 {
2021 $uuid = Str::uuid();
2022
2023 Str::createUuidsUsing(fn () => $uuid);
2024
2025 if ($callback !== null) {
2026 try {
2027 $callback($uuid);
2028 } finally {
2029 Str::createUuidsNormally();
2030 }
2031 }
2032
2033 return $uuid;
2034 }
2035
2036 /**
2037 * Indicate that UUIDs should be created normally and not using a custom factory.
2038 *
2039 * @return void
2040 */
2041 public static function createUuidsNormally()
2042 {
2043 static::$uuidFactory = null;
2044 }
2045
2046 /**
2047 * Generate a ULID.
2048 *
2049 * @param \DateTimeInterface|null $time
2050 * @return \Symfony\Component\Uid\Ulid
2051 */
2052 public static function ulid($time = null)
2053 {
2054 if (static::$ulidFactory) {
2055 return call_user_func(static::$ulidFactory);
2056 }
2057
2058 if ($time === null) {
2059 return new Ulid();
2060 }
2061
2062 return new Ulid(Ulid::generate($time));
2063 }
2064
2065 /**
2066 * Indicate that ULIDs should be created normally and not using a custom factory.
2067 *
2068 * @return void
2069 */
2070 public static function createUlidsNormally()
2071 {
2072 static::$ulidFactory = null;
2073 }
2074
2075 /**
2076 * Set the callable that will be used to generate ULIDs.
2077 *
2078 * @param (callable(): \Symfony\Component\Uid\Ulid)|null $factory
2079 * @return void
2080 */
2081 public static function createUlidsUsing(?callable $factory = null)
2082 {
2083 static::$ulidFactory = $factory;
2084 }
2085
2086 /**
2087 * Set the sequence that will be used to generate ULIDs.
2088 *
2089 * @param \Symfony\Component\Uid\Ulid[] $sequence
2090 * @param (callable(): \Symfony\Component\Uid\Ulid)|null $whenMissing
2091 * @return void
2092 */
2093 public static function createUlidsUsingSequence(array $sequence, $whenMissing = null)
2094 {
2095 $next = 0;
2096
2097 $whenMissing ??= function () use (&$next) {
2098 $factoryCache = static::$ulidFactory;
2099
2100 static::$ulidFactory = null;
2101
2102 $ulid = static::ulid();
2103
2104 static::$ulidFactory = $factoryCache;
2105
2106 $next++;
2107
2108 return $ulid;
2109 };
2110
2111 static::createUlidsUsing(function () use (&$next, $sequence, $whenMissing) {
2112 if (array_key_exists($next, $sequence)) {
2113 return $sequence[$next++];
2114 }
2115
2116 return $whenMissing();
2117 });
2118 }
2119
2120 /**
2121 * Always return the same ULID when generating new ULIDs.
2122 *
2123 * @param (Closure(Ulid): mixed)|null $callback
2124 * @return Ulid
2125 */
2126 public static function freezeUlids(?Closure $callback = null)
2127 {
2128 $ulid = Str::ulid();
2129
2130 Str::createUlidsUsing(fn () => $ulid);
2131
2132 if ($callback !== null) {
2133 try {
2134 $callback($ulid);
2135 } finally {
2136 Str::createUlidsNormally();
2137 }
2138 }
2139
2140 return $ulid;
2141 }
2142
2143 /**
2144 * Remove all strings from the casing caches.
2145 *
2146 * @return void
2147 */
2148 public static function flushCache()
2149 {
2150 static::$snakeCache = [];
2151 static::$camelCache = [];
2152 static::$studlyCache = [];
2153 }
2154 }