Str.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950
  1. <?php
  2. namespace Illuminate\Support;
  3. use Closure;
  4. use Illuminate\Support\Traits\Macroable;
  5. use JsonException;
  6. use League\CommonMark\Environment\Environment;
  7. use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
  8. use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension;
  9. use League\CommonMark\GithubFlavoredMarkdownConverter;
  10. use League\CommonMark\MarkdownConverter;
  11. use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
  12. use Ramsey\Uuid\Generator\CombGenerator;
  13. use Ramsey\Uuid\Uuid;
  14. use Ramsey\Uuid\UuidFactory;
  15. use Symfony\Component\Uid\Ulid;
  16. use Throwable;
  17. use Traversable;
  18. use voku\helper\ASCII;
  19. class Str
  20. {
  21. use Macroable;
  22. /**
  23. * The cache of snake-cased words.
  24. *
  25. * @var array
  26. */
  27. protected static $snakeCache = [];
  28. /**
  29. * The cache of camel-cased words.
  30. *
  31. * @var array
  32. */
  33. protected static $camelCache = [];
  34. /**
  35. * The cache of studly-cased words.
  36. *
  37. * @var array
  38. */
  39. protected static $studlyCache = [];
  40. /**
  41. * The callback that should be used to generate UUIDs.
  42. *
  43. * @var callable|null
  44. */
  45. protected static $uuidFactory;
  46. /**
  47. * The callback that should be used to generate ULIDs.
  48. *
  49. * @var callable|null
  50. */
  51. protected static $ulidFactory;
  52. /**
  53. * The callback that should be used to generate random strings.
  54. *
  55. * @var callable|null
  56. */
  57. protected static $randomStringFactory;
  58. /**
  59. * Get a new stringable object from the given string.
  60. *
  61. * @param string $string
  62. * @return \Illuminate\Support\Stringable
  63. */
  64. public static function of($string)
  65. {
  66. return new Stringable($string);
  67. }
  68. /**
  69. * Return the remainder of a string after the first occurrence of a given value.
  70. *
  71. * @param string $subject
  72. * @param string $search
  73. * @return string
  74. */
  75. public static function after($subject, $search)
  76. {
  77. return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0];
  78. }
  79. /**
  80. * Return the remainder of a string after the last occurrence of a given value.
  81. *
  82. * @param string $subject
  83. * @param string $search
  84. * @return string
  85. */
  86. public static function afterLast($subject, $search)
  87. {
  88. if ($search === '') {
  89. return $subject;
  90. }
  91. $position = strrpos($subject, (string) $search);
  92. if ($position === false) {
  93. return $subject;
  94. }
  95. return substr($subject, $position + strlen($search));
  96. }
  97. /**
  98. * Transliterate a UTF-8 value to ASCII.
  99. *
  100. * @param string $value
  101. * @param string $language
  102. * @return string
  103. */
  104. public static function ascii($value, $language = 'en')
  105. {
  106. return ASCII::to_ascii((string) $value, $language);
  107. }
  108. /**
  109. * Transliterate a string to its closest ASCII representation.
  110. *
  111. * @param string $string
  112. * @param string|null $unknown
  113. * @param bool|null $strict
  114. * @return string
  115. */
  116. public static function transliterate($string, $unknown = '?', $strict = false)
  117. {
  118. return ASCII::to_transliterate($string, $unknown, $strict);
  119. }
  120. /**
  121. * Get the portion of a string before the first occurrence of a given value.
  122. *
  123. * @param string $subject
  124. * @param string $search
  125. * @return string
  126. */
  127. public static function before($subject, $search)
  128. {
  129. if ($search === '') {
  130. return $subject;
  131. }
  132. $result = strstr($subject, (string) $search, true);
  133. return $result === false ? $subject : $result;
  134. }
  135. /**
  136. * Get the portion of a string before the last occurrence of a given value.
  137. *
  138. * @param string $subject
  139. * @param string $search
  140. * @return string
  141. */
  142. public static function beforeLast($subject, $search)
  143. {
  144. if ($search === '') {
  145. return $subject;
  146. }
  147. $pos = mb_strrpos($subject, $search);
  148. if ($pos === false) {
  149. return $subject;
  150. }
  151. return static::substr($subject, 0, $pos);
  152. }
  153. /**
  154. * Get the portion of a string between two given values.
  155. *
  156. * @param string $subject
  157. * @param string $from
  158. * @param string $to
  159. * @return string
  160. */
  161. public static function between($subject, $from, $to)
  162. {
  163. if ($from === '' || $to === '') {
  164. return $subject;
  165. }
  166. return static::beforeLast(static::after($subject, $from), $to);
  167. }
  168. /**
  169. * Get the smallest possible portion of a string between two given values.
  170. *
  171. * @param string $subject
  172. * @param string $from
  173. * @param string $to
  174. * @return string
  175. */
  176. public static function betweenFirst($subject, $from, $to)
  177. {
  178. if ($from === '' || $to === '') {
  179. return $subject;
  180. }
  181. return static::before(static::after($subject, $from), $to);
  182. }
  183. /**
  184. * Convert a value to camel case.
  185. *
  186. * @param string $value
  187. * @return string
  188. */
  189. public static function camel($value)
  190. {
  191. if (isset(static::$camelCache[$value])) {
  192. return static::$camelCache[$value];
  193. }
  194. return static::$camelCache[$value] = lcfirst(static::studly($value));
  195. }
  196. /**
  197. * Get the character at the specified index.
  198. *
  199. * @param string $subject
  200. * @param int $index
  201. * @return string|false
  202. */
  203. public static function charAt($subject, $index)
  204. {
  205. $length = mb_strlen($subject);
  206. if ($index < 0 ? $index < -$length : $index > $length - 1) {
  207. return false;
  208. }
  209. return mb_substr($subject, $index, 1);
  210. }
  211. /**
  212. * Remove the given string(s) if it exists at the start of the haystack.
  213. *
  214. * @param string $subject
  215. * @param string|array $needle
  216. * @return string
  217. */
  218. public static function chopStart($subject, $needle)
  219. {
  220. foreach ((array) $needle as $n) {
  221. if (str_starts_with($subject, $n)) {
  222. return substr($subject, strlen($n));
  223. }
  224. }
  225. return $subject;
  226. }
  227. /**
  228. * Remove the given string(s) if it exists at the end of the haystack.
  229. *
  230. * @param string $subject
  231. * @param string|array $needle
  232. * @return string
  233. */
  234. public static function chopEnd($subject, $needle)
  235. {
  236. foreach ((array) $needle as $n) {
  237. if (str_ends_with($subject, $n)) {
  238. return substr($subject, 0, -strlen($n));
  239. }
  240. }
  241. return $subject;
  242. }
  243. /**
  244. * Determine if a given string contains a given substring.
  245. *
  246. * @param string $haystack
  247. * @param string|iterable<string> $needles
  248. * @param bool $ignoreCase
  249. * @return bool
  250. */
  251. public static function contains($haystack, $needles, $ignoreCase = false)
  252. {
  253. if ($ignoreCase) {
  254. $haystack = mb_strtolower($haystack);
  255. }
  256. if (! is_iterable($needles)) {
  257. $needles = (array) $needles;
  258. }
  259. foreach ($needles as $needle) {
  260. if ($ignoreCase) {
  261. $needle = mb_strtolower($needle);
  262. }
  263. if ($needle !== '' && str_contains($haystack, $needle)) {
  264. return true;
  265. }
  266. }
  267. return false;
  268. }
  269. /**
  270. * Determine if a given string contains all array values.
  271. *
  272. * @param string $haystack
  273. * @param iterable<string> $needles
  274. * @param bool $ignoreCase
  275. * @return bool
  276. */
  277. public static function containsAll($haystack, $needles, $ignoreCase = false)
  278. {
  279. foreach ($needles as $needle) {
  280. if (! static::contains($haystack, $needle, $ignoreCase)) {
  281. return false;
  282. }
  283. }
  284. return true;
  285. }
  286. /**
  287. * Convert the case of a string.
  288. *
  289. * @param string $string
  290. * @param int $mode
  291. * @param string|null $encoding
  292. * @return string
  293. */
  294. public static function convertCase(string $string, int $mode = MB_CASE_FOLD, ?string $encoding = 'UTF-8')
  295. {
  296. return mb_convert_case($string, $mode, $encoding);
  297. }
  298. /**
  299. * Determine if a given string ends with a given substring.
  300. *
  301. * @param string $haystack
  302. * @param string|iterable<string> $needles
  303. * @return bool
  304. */
  305. public static function endsWith($haystack, $needles)
  306. {
  307. if (! is_iterable($needles)) {
  308. $needles = (array) $needles;
  309. }
  310. foreach ($needles as $needle) {
  311. if ((string) $needle !== '' && str_ends_with($haystack, $needle)) {
  312. return true;
  313. }
  314. }
  315. return false;
  316. }
  317. /**
  318. * Extracts an excerpt from text that matches the first instance of a phrase.
  319. *
  320. * @param string $text
  321. * @param string $phrase
  322. * @param array $options
  323. * @return string|null
  324. */
  325. public static function excerpt($text, $phrase = '', $options = [])
  326. {
  327. $radius = $options['radius'] ?? 100;
  328. $omission = $options['omission'] ?? '...';
  329. preg_match('/^(.*?)('.preg_quote((string) $phrase, '/').')(.*)$/iu', (string) $text, $matches);
  330. if (empty($matches)) {
  331. return null;
  332. }
  333. $start = ltrim($matches[1]);
  334. $start = str(mb_substr($start, max(mb_strlen($start, 'UTF-8') - $radius, 0), $radius, 'UTF-8'))->ltrim()->unless(
  335. fn ($startWithRadius) => $startWithRadius->exactly($start),
  336. fn ($startWithRadius) => $startWithRadius->prepend($omission),
  337. );
  338. $end = rtrim($matches[3]);
  339. $end = str(mb_substr($end, 0, $radius, 'UTF-8'))->rtrim()->unless(
  340. fn ($endWithRadius) => $endWithRadius->exactly($end),
  341. fn ($endWithRadius) => $endWithRadius->append($omission),
  342. );
  343. return $start->append($matches[2], $end)->toString();
  344. }
  345. /**
  346. * Cap a string with a single instance of a given value.
  347. *
  348. * @param string $value
  349. * @param string $cap
  350. * @return string
  351. */
  352. public static function finish($value, $cap)
  353. {
  354. $quoted = preg_quote($cap, '/');
  355. return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap;
  356. }
  357. /**
  358. * Wrap the string with the given strings.
  359. *
  360. * @param string $value
  361. * @param string $before
  362. * @param string|null $after
  363. * @return string
  364. */
  365. public static function wrap($value, $before, $after = null)
  366. {
  367. return $before.$value.($after ??= $before);
  368. }
  369. /**
  370. * Unwrap the string with the given strings.
  371. *
  372. * @param string $value
  373. * @param string $before
  374. * @param string|null $after
  375. * @return string
  376. */
  377. public static function unwrap($value, $before, $after = null)
  378. {
  379. if (static::startsWith($value, $before)) {
  380. $value = static::substr($value, static::length($before));
  381. }
  382. if (static::endsWith($value, $after ??= $before)) {
  383. $value = static::substr($value, 0, -static::length($after));
  384. }
  385. return $value;
  386. }
  387. /**
  388. * Determine if a given string matches a given pattern.
  389. *
  390. * @param string|iterable<string> $pattern
  391. * @param string $value
  392. * @return bool
  393. */
  394. public static function is($pattern, $value)
  395. {
  396. $value = (string) $value;
  397. if (! is_iterable($pattern)) {
  398. $pattern = [$pattern];
  399. }
  400. foreach ($pattern as $pattern) {
  401. $pattern = (string) $pattern;
  402. // If the given value is an exact match we can of course return true right
  403. // from the beginning. Otherwise, we will translate asterisks and do an
  404. // actual pattern match against the two strings to see if they match.
  405. if ($pattern === $value) {
  406. return true;
  407. }
  408. $pattern = preg_quote($pattern, '#');
  409. // Asterisks are translated into zero-or-more regular expression wildcards
  410. // to make it convenient to check if the strings starts with the given
  411. // pattern such as "library/*", making any string check convenient.
  412. $pattern = str_replace('\*', '.*', $pattern);
  413. if (preg_match('#^'.$pattern.'\z#u', $value) === 1) {
  414. return true;
  415. }
  416. }
  417. return false;
  418. }
  419. /**
  420. * Determine if a given string is 7 bit ASCII.
  421. *
  422. * @param string $value
  423. * @return bool
  424. */
  425. public static function isAscii($value)
  426. {
  427. return ASCII::is_ascii((string) $value);
  428. }
  429. /**
  430. * Determine if a given value is valid JSON.
  431. *
  432. * @param mixed $value
  433. * @return bool
  434. */
  435. public static function isJson($value)
  436. {
  437. if (! is_string($value)) {
  438. return false;
  439. }
  440. if (function_exists('json_validate')) {
  441. return json_validate($value, 512);
  442. }
  443. try {
  444. json_decode($value, true, 512, JSON_THROW_ON_ERROR);
  445. } catch (JsonException) {
  446. return false;
  447. }
  448. return true;
  449. }
  450. /**
  451. * Determine if a given value is a valid URL.
  452. *
  453. * @param mixed $value
  454. * @param array $protocols
  455. * @return bool
  456. */
  457. public static function isUrl($value, array $protocols = [])
  458. {
  459. if (! is_string($value)) {
  460. return false;
  461. }
  462. $protocolList = empty($protocols)
  463. ? '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'
  464. : implode('|', $protocols);
  465. /*
  466. * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (5.0.7).
  467. *
  468. * (c) Fabien Potencier <fabien@symfony.com> http://symfony.com
  469. */
  470. $pattern = '~^
  471. (LARAVEL_PROTOCOLS):// # protocol
  472. (((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+)@)? # basic auth
  473. (
  474. ([\pL\pN\pS\-\_\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name
  475. | # or
  476. \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address
  477. | # or
  478. \[
  479. (?:(?:(?:(?:(?:(?:(?:[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})))?::))))
  480. \] # an IPv6 address
  481. )
  482. (:[0-9]+)? # a port (optional)
  483. (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})* )* # a path
  484. (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a query (optional)
  485. (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a fragment (optional)
  486. $~ixu';
  487. return preg_match(str_replace('LARAVEL_PROTOCOLS', $protocolList, $pattern), $value) > 0;
  488. }
  489. /**
  490. * Determine if a given value is a valid UUID.
  491. *
  492. * @param mixed $value
  493. * @return bool
  494. */
  495. public static function isUuid($value)
  496. {
  497. if (! is_string($value)) {
  498. return false;
  499. }
  500. 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;
  501. }
  502. /**
  503. * Determine if a given value is a valid ULID.
  504. *
  505. * @param mixed $value
  506. * @return bool
  507. */
  508. public static function isUlid($value)
  509. {
  510. if (! is_string($value)) {
  511. return false;
  512. }
  513. return Ulid::isValid($value);
  514. }
  515. /**
  516. * Convert a string to kebab case.
  517. *
  518. * @param string $value
  519. * @return string
  520. */
  521. public static function kebab($value)
  522. {
  523. return static::snake($value, '-');
  524. }
  525. /**
  526. * Return the length of the given string.
  527. *
  528. * @param string $value
  529. * @param string|null $encoding
  530. * @return int
  531. */
  532. public static function length($value, $encoding = null)
  533. {
  534. return mb_strlen($value, $encoding);
  535. }
  536. /**
  537. * Limit the number of characters in a string.
  538. *
  539. * @param string $value
  540. * @param int $limit
  541. * @param string $end
  542. * @return string
  543. */
  544. public static function limit($value, $limit = 100, $end = '...')
  545. {
  546. if (mb_strwidth($value, 'UTF-8') <= $limit) {
  547. return $value;
  548. }
  549. return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
  550. }
  551. /**
  552. * Convert the given string to lower-case.
  553. *
  554. * @param string $value
  555. * @return string
  556. */
  557. public static function lower($value)
  558. {
  559. return mb_strtolower($value, 'UTF-8');
  560. }
  561. /**
  562. * Limit the number of words in a string.
  563. *
  564. * @param string $value
  565. * @param int $words
  566. * @param string $end
  567. * @return string
  568. */
  569. public static function words($value, $words = 100, $end = '...')
  570. {
  571. preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
  572. if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
  573. return $value;
  574. }
  575. return rtrim($matches[0]).$end;
  576. }
  577. /**
  578. * Converts GitHub flavored Markdown into HTML.
  579. *
  580. * @param string $string
  581. * @param array $options
  582. * @param array $extensions
  583. * @return string
  584. */
  585. public static function markdown($string, array $options = [], array $extensions = [])
  586. {
  587. $converter = new GithubFlavoredMarkdownConverter($options);
  588. $environment = $converter->getEnvironment();
  589. foreach ($extensions as $extension) {
  590. $environment->addExtension($extension);
  591. }
  592. return (string) $converter->convert($string);
  593. }
  594. /**
  595. * Converts inline Markdown into HTML.
  596. *
  597. * @param string $string
  598. * @param array $options
  599. * @return string
  600. */
  601. public static function inlineMarkdown($string, array $options = [])
  602. {
  603. $environment = new Environment($options);
  604. $environment->addExtension(new GithubFlavoredMarkdownExtension());
  605. $environment->addExtension(new InlinesOnlyExtension());
  606. $converter = new MarkdownConverter($environment);
  607. return (string) $converter->convert($string);
  608. }
  609. /**
  610. * Masks a portion of a string with a repeated character.
  611. *
  612. * @param string $string
  613. * @param string $character
  614. * @param int $index
  615. * @param int|null $length
  616. * @param string $encoding
  617. * @return string
  618. */
  619. public static function mask($string, $character, $index, $length = null, $encoding = 'UTF-8')
  620. {
  621. if ($character === '') {
  622. return $string;
  623. }
  624. $segment = mb_substr($string, $index, $length, $encoding);
  625. if ($segment === '') {
  626. return $string;
  627. }
  628. $strlen = mb_strlen($string, $encoding);
  629. $startIndex = $index;
  630. if ($index < 0) {
  631. $startIndex = $index < -$strlen ? 0 : $strlen + $index;
  632. }
  633. $start = mb_substr($string, 0, $startIndex, $encoding);
  634. $segmentLen = mb_strlen($segment, $encoding);
  635. $end = mb_substr($string, $startIndex + $segmentLen);
  636. return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end;
  637. }
  638. /**
  639. * Get the string matching the given pattern.
  640. *
  641. * @param string $pattern
  642. * @param string $subject
  643. * @return string
  644. */
  645. public static function match($pattern, $subject)
  646. {
  647. preg_match($pattern, $subject, $matches);
  648. if (! $matches) {
  649. return '';
  650. }
  651. return $matches[1] ?? $matches[0];
  652. }
  653. /**
  654. * Determine if a given string matches a given pattern.
  655. *
  656. * @param string|iterable<string> $pattern
  657. * @param string $value
  658. * @return bool
  659. */
  660. public static function isMatch($pattern, $value)
  661. {
  662. $value = (string) $value;
  663. if (! is_iterable($pattern)) {
  664. $pattern = [$pattern];
  665. }
  666. foreach ($pattern as $pattern) {
  667. $pattern = (string) $pattern;
  668. if (preg_match($pattern, $value) === 1) {
  669. return true;
  670. }
  671. }
  672. return false;
  673. }
  674. /**
  675. * Get the string matching the given pattern.
  676. *
  677. * @param string $pattern
  678. * @param string $subject
  679. * @return \Illuminate\Support\Collection
  680. */
  681. public static function matchAll($pattern, $subject)
  682. {
  683. preg_match_all($pattern, $subject, $matches);
  684. if (empty($matches[0])) {
  685. return collect();
  686. }
  687. return collect($matches[1] ?? $matches[0]);
  688. }
  689. /**
  690. * Remove all non-numeric characters from a string.
  691. *
  692. * @param string $value
  693. * @return string
  694. */
  695. public static function numbers($value)
  696. {
  697. return preg_replace('/[^0-9]/', '', $value);
  698. }
  699. /**
  700. * Pad both sides of a string with another.
  701. *
  702. * @param string $value
  703. * @param int $length
  704. * @param string $pad
  705. * @return string
  706. */
  707. public static function padBoth($value, $length, $pad = ' ')
  708. {
  709. if (function_exists('mb_str_pad')) {
  710. return mb_str_pad($value, $length, $pad, STR_PAD_BOTH);
  711. }
  712. $short = max(0, $length - mb_strlen($value));
  713. $shortLeft = floor($short / 2);
  714. $shortRight = ceil($short / 2);
  715. return mb_substr(str_repeat($pad, $shortLeft), 0, $shortLeft).
  716. $value.
  717. mb_substr(str_repeat($pad, $shortRight), 0, $shortRight);
  718. }
  719. /**
  720. * Pad the left side of a string with another.
  721. *
  722. * @param string $value
  723. * @param int $length
  724. * @param string $pad
  725. * @return string
  726. */
  727. public static function padLeft($value, $length, $pad = ' ')
  728. {
  729. if (function_exists('mb_str_pad')) {
  730. return mb_str_pad($value, $length, $pad, STR_PAD_LEFT);
  731. }
  732. $short = max(0, $length - mb_strlen($value));
  733. return mb_substr(str_repeat($pad, $short), 0, $short).$value;
  734. }
  735. /**
  736. * Pad the right side of a string with another.
  737. *
  738. * @param string $value
  739. * @param int $length
  740. * @param string $pad
  741. * @return string
  742. */
  743. public static function padRight($value, $length, $pad = ' ')
  744. {
  745. if (function_exists('mb_str_pad')) {
  746. return mb_str_pad($value, $length, $pad, STR_PAD_RIGHT);
  747. }
  748. $short = max(0, $length - mb_strlen($value));
  749. return $value.mb_substr(str_repeat($pad, $short), 0, $short);
  750. }
  751. /**
  752. * Parse a Class[@]method style callback into class and method.
  753. *
  754. * @param string $callback
  755. * @param string|null $default
  756. * @return array<int, string|null>
  757. */
  758. public static function parseCallback($callback, $default = null)
  759. {
  760. if (static::contains($callback, "@anonymous\0")) {
  761. if (static::substrCount($callback, '@') > 1) {
  762. return [
  763. static::beforeLast($callback, '@'),
  764. static::afterLast($callback, '@'),
  765. ];
  766. }
  767. return [$callback, $default];
  768. }
  769. return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default];
  770. }
  771. /**
  772. * Get the plural form of an English word.
  773. *
  774. * @param string $value
  775. * @param int|array|\Countable $count
  776. * @return string
  777. */
  778. public static function plural($value, $count = 2)
  779. {
  780. return Pluralizer::plural($value, $count);
  781. }
  782. /**
  783. * Pluralize the last word of an English, studly caps case string.
  784. *
  785. * @param string $value
  786. * @param int|array|\Countable $count
  787. * @return string
  788. */
  789. public static function pluralStudly($value, $count = 2)
  790. {
  791. $parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
  792. $lastWord = array_pop($parts);
  793. return implode('', $parts).self::plural($lastWord, $count);
  794. }
  795. /**
  796. * Generate a random, secure password.
  797. *
  798. * @param int $length
  799. * @param bool $letters
  800. * @param bool $numbers
  801. * @param bool $symbols
  802. * @param bool $spaces
  803. * @return string
  804. */
  805. public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false)
  806. {
  807. $password = new Collection();
  808. $options = (new Collection([
  809. 'letters' => $letters === true ? [
  810. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
  811. 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  812. 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
  813. 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  814. 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  815. ] : null,
  816. 'numbers' => $numbers === true ? [
  817. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  818. ] : null,
  819. 'symbols' => $symbols === true ? [
  820. '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-',
  821. '_', '.', ',', '<', '>', '?', '/', '\\', '{', '}', '[',
  822. ']', '|', ':', ';',
  823. ] : null,
  824. 'spaces' => $spaces === true ? [' '] : null,
  825. ]))->filter()->each(fn ($c) => $password->push($c[random_int(0, count($c) - 1)])
  826. )->flatten();
  827. $length = $length - $password->count();
  828. return $password->merge($options->pipe(
  829. fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)])
  830. ))->shuffle()->implode('');
  831. }
  832. /**
  833. * Find the multi-byte safe position of the first occurrence of a given substring in a string.
  834. *
  835. * @param string $haystack
  836. * @param string $needle
  837. * @param int $offset
  838. * @param string|null $encoding
  839. * @return int|false
  840. */
  841. public static function position($haystack, $needle, $offset = 0, $encoding = null)
  842. {
  843. return mb_strpos($haystack, (string) $needle, $offset, $encoding);
  844. }
  845. /**
  846. * Generate a more truly "random" alpha-numeric string.
  847. *
  848. * @param int $length
  849. * @return string
  850. */
  851. public static function random($length = 16)
  852. {
  853. return (static::$randomStringFactory ?? function ($length) {
  854. $string = '';
  855. while (($len = strlen($string)) < $length) {
  856. $size = $length - $len;
  857. $bytesSize = (int) ceil($size / 3) * 3;
  858. $bytes = random_bytes($bytesSize);
  859. $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
  860. }
  861. return $string;
  862. })($length);
  863. }
  864. /**
  865. * Set the callable that will be used to generate random strings.
  866. *
  867. * @param callable|null $factory
  868. * @return void
  869. */
  870. public static function createRandomStringsUsing(?callable $factory = null)
  871. {
  872. static::$randomStringFactory = $factory;
  873. }
  874. /**
  875. * Set the sequence that will be used to generate random strings.
  876. *
  877. * @param array $sequence
  878. * @param callable|null $whenMissing
  879. * @return void
  880. */
  881. public static function createRandomStringsUsingSequence(array $sequence, $whenMissing = null)
  882. {
  883. $next = 0;
  884. $whenMissing ??= function ($length) use (&$next) {
  885. $factoryCache = static::$randomStringFactory;
  886. static::$randomStringFactory = null;
  887. $randomString = static::random($length);
  888. static::$randomStringFactory = $factoryCache;
  889. $next++;
  890. return $randomString;
  891. };
  892. static::createRandomStringsUsing(function ($length) use (&$next, $sequence, $whenMissing) {
  893. if (array_key_exists($next, $sequence)) {
  894. return $sequence[$next++];
  895. }
  896. return $whenMissing($length);
  897. });
  898. }
  899. /**
  900. * Indicate that random strings should be created normally and not using a custom factory.
  901. *
  902. * @return void
  903. */
  904. public static function createRandomStringsNormally()
  905. {
  906. static::$randomStringFactory = null;
  907. }
  908. /**
  909. * Repeat the given string.
  910. *
  911. * @param string $string
  912. * @param int $times
  913. * @return string
  914. */
  915. public static function repeat(string $string, int $times)
  916. {
  917. return str_repeat($string, $times);
  918. }
  919. /**
  920. * Replace a given value in the string sequentially with an array.
  921. *
  922. * @param string $search
  923. * @param iterable<string> $replace
  924. * @param string $subject
  925. * @return string
  926. */
  927. public static function replaceArray($search, $replace, $subject)
  928. {
  929. if ($replace instanceof Traversable) {
  930. $replace = collect($replace)->all();
  931. }
  932. $segments = explode($search, $subject);
  933. $result = array_shift($segments);
  934. foreach ($segments as $segment) {
  935. $result .= self::toStringOr(array_shift($replace) ?? $search, $search).$segment;
  936. }
  937. return $result;
  938. }
  939. /**
  940. * Convert the given value to a string or return the given fallback on failure.
  941. *
  942. * @param mixed $value
  943. * @param string $fallback
  944. * @return string
  945. */
  946. private static function toStringOr($value, $fallback)
  947. {
  948. try {
  949. return (string) $value;
  950. } catch (Throwable $e) {
  951. return $fallback;
  952. }
  953. }
  954. /**
  955. * Replace the given value in the given string.
  956. *
  957. * @param string|iterable<string> $search
  958. * @param string|iterable<string> $replace
  959. * @param string|iterable<string> $subject
  960. * @param bool $caseSensitive
  961. * @return string|string[]
  962. */
  963. public static function replace($search, $replace, $subject, $caseSensitive = true)
  964. {
  965. if ($search instanceof Traversable) {
  966. $search = collect($search)->all();
  967. }
  968. if ($replace instanceof Traversable) {
  969. $replace = collect($replace)->all();
  970. }
  971. if ($subject instanceof Traversable) {
  972. $subject = collect($subject)->all();
  973. }
  974. return $caseSensitive
  975. ? str_replace($search, $replace, $subject)
  976. : str_ireplace($search, $replace, $subject);
  977. }
  978. /**
  979. * Replace the first occurrence of a given value in the string.
  980. *
  981. * @param string $search
  982. * @param string $replace
  983. * @param string $subject
  984. * @return string
  985. */
  986. public static function replaceFirst($search, $replace, $subject)
  987. {
  988. $search = (string) $search;
  989. if ($search === '') {
  990. return $subject;
  991. }
  992. $position = strpos($subject, $search);
  993. if ($position !== false) {
  994. return substr_replace($subject, $replace, $position, strlen($search));
  995. }
  996. return $subject;
  997. }
  998. /**
  999. * Replace the first occurrence of the given value if it appears at the start of the string.
  1000. *
  1001. * @param string $search
  1002. * @param string $replace
  1003. * @param string $subject
  1004. * @return string
  1005. */
  1006. public static function replaceStart($search, $replace, $subject)
  1007. {
  1008. $search = (string) $search;
  1009. if ($search === '') {
  1010. return $subject;
  1011. }
  1012. if (static::startsWith($subject, $search)) {
  1013. return static::replaceFirst($search, $replace, $subject);
  1014. }
  1015. return $subject;
  1016. }
  1017. /**
  1018. * Replace the last occurrence of a given value in the string.
  1019. *
  1020. * @param string $search
  1021. * @param string $replace
  1022. * @param string $subject
  1023. * @return string
  1024. */
  1025. public static function replaceLast($search, $replace, $subject)
  1026. {
  1027. $search = (string) $search;
  1028. if ($search === '') {
  1029. return $subject;
  1030. }
  1031. $position = strrpos($subject, $search);
  1032. if ($position !== false) {
  1033. return substr_replace($subject, $replace, $position, strlen($search));
  1034. }
  1035. return $subject;
  1036. }
  1037. /**
  1038. * Replace the last occurrence of a given value if it appears at the end of the string.
  1039. *
  1040. * @param string $search
  1041. * @param string $replace
  1042. * @param string $subject
  1043. * @return string
  1044. */
  1045. public static function replaceEnd($search, $replace, $subject)
  1046. {
  1047. $search = (string) $search;
  1048. if ($search === '') {
  1049. return $subject;
  1050. }
  1051. if (static::endsWith($subject, $search)) {
  1052. return static::replaceLast($search, $replace, $subject);
  1053. }
  1054. return $subject;
  1055. }
  1056. /**
  1057. * Replace the patterns matching the given regular expression.
  1058. *
  1059. * @param array|string $pattern
  1060. * @param \Closure|string[]|string $replace
  1061. * @param array|string $subject
  1062. * @param int $limit
  1063. * @return string|string[]|null
  1064. */
  1065. public static function replaceMatches($pattern, $replace, $subject, $limit = -1)
  1066. {
  1067. if ($replace instanceof Closure) {
  1068. return preg_replace_callback($pattern, $replace, $subject, $limit);
  1069. }
  1070. return preg_replace($pattern, $replace, $subject, $limit);
  1071. }
  1072. /**
  1073. * Remove any occurrence of the given string in the subject.
  1074. *
  1075. * @param string|iterable<string> $search
  1076. * @param string|iterable<string> $subject
  1077. * @param bool $caseSensitive
  1078. * @return string
  1079. */
  1080. public static function remove($search, $subject, $caseSensitive = true)
  1081. {
  1082. if ($search instanceof Traversable) {
  1083. $search = collect($search)->all();
  1084. }
  1085. return $caseSensitive
  1086. ? str_replace($search, '', $subject)
  1087. : str_ireplace($search, '', $subject);
  1088. }
  1089. /**
  1090. * Reverse the given string.
  1091. *
  1092. * @param string $value
  1093. * @return string
  1094. */
  1095. public static function reverse(string $value)
  1096. {
  1097. return implode(array_reverse(mb_str_split($value)));
  1098. }
  1099. /**
  1100. * Begin a string with a single instance of a given value.
  1101. *
  1102. * @param string $value
  1103. * @param string $prefix
  1104. * @return string
  1105. */
  1106. public static function start($value, $prefix)
  1107. {
  1108. $quoted = preg_quote($prefix, '/');
  1109. return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value);
  1110. }
  1111. /**
  1112. * Convert the given string to upper-case.
  1113. *
  1114. * @param string $value
  1115. * @return string
  1116. */
  1117. public static function upper($value)
  1118. {
  1119. return mb_strtoupper($value, 'UTF-8');
  1120. }
  1121. /**
  1122. * Convert the given string to proper case.
  1123. *
  1124. * @param string $value
  1125. * @return string
  1126. */
  1127. public static function title($value)
  1128. {
  1129. return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
  1130. }
  1131. /**
  1132. * Convert the given string to proper case for each word.
  1133. *
  1134. * @param string $value
  1135. * @return string
  1136. */
  1137. public static function headline($value)
  1138. {
  1139. $parts = explode(' ', $value);
  1140. $parts = count($parts) > 1
  1141. ? array_map([static::class, 'title'], $parts)
  1142. : array_map([static::class, 'title'], static::ucsplit(implode('_', $parts)));
  1143. $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts));
  1144. return implode(' ', array_filter(explode('_', $collapsed)));
  1145. }
  1146. /**
  1147. * Convert the given string to APA-style title case.
  1148. *
  1149. * See: https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case
  1150. *
  1151. * @param string $value
  1152. * @return string
  1153. */
  1154. public static function apa($value)
  1155. {
  1156. if (trim($value) === '') {
  1157. return $value;
  1158. }
  1159. $minorWords = [
  1160. 'and', 'as', 'but', 'for', 'if', 'nor', 'or', 'so', 'yet', 'a', 'an',
  1161. 'the', 'at', 'by', 'for', 'in', 'of', 'off', 'on', 'per', 'to', 'up', 'via',
  1162. 'et', 'ou', 'un', 'une', 'la', 'le', 'les', 'de', 'du', 'des', 'par', 'à',
  1163. ];
  1164. $endPunctuation = ['.', '!', '?', ':', '—', ','];
  1165. $words = preg_split('/\s+/', $value, -1, PREG_SPLIT_NO_EMPTY);
  1166. for ($i = 0; $i < count($words); $i++) {
  1167. $lowercaseWord = mb_strtolower($words[$i]);
  1168. if (str_contains($lowercaseWord, '-')) {
  1169. $hyphenatedWords = explode('-', $lowercaseWord);
  1170. $hyphenatedWords = array_map(function ($part) use ($minorWords) {
  1171. return (in_array($part, $minorWords) && mb_strlen($part) <= 3)
  1172. ? $part
  1173. : mb_strtoupper(mb_substr($part, 0, 1)).mb_substr($part, 1);
  1174. }, $hyphenatedWords);
  1175. $words[$i] = implode('-', $hyphenatedWords);
  1176. } else {
  1177. if (in_array($lowercaseWord, $minorWords) &&
  1178. mb_strlen($lowercaseWord) <= 3 &&
  1179. ! ($i === 0 || in_array(mb_substr($words[$i - 1], -1), $endPunctuation))) {
  1180. $words[$i] = $lowercaseWord;
  1181. } else {
  1182. $words[$i] = mb_strtoupper(mb_substr($lowercaseWord, 0, 1)).mb_substr($lowercaseWord, 1);
  1183. }
  1184. }
  1185. }
  1186. return implode(' ', $words);
  1187. }
  1188. /**
  1189. * Get the singular form of an English word.
  1190. *
  1191. * @param string $value
  1192. * @return string
  1193. */
  1194. public static function singular($value)
  1195. {
  1196. return Pluralizer::singular($value);
  1197. }
  1198. /**
  1199. * Generate a URL friendly "slug" from a given string.
  1200. *
  1201. * @param string $title
  1202. * @param string $separator
  1203. * @param string|null $language
  1204. * @param array<string, string> $dictionary
  1205. * @return string
  1206. */
  1207. public static function slug($title, $separator = '-', $language = 'en', $dictionary = ['@' => 'at'])
  1208. {
  1209. $title = $language ? static::ascii($title, $language) : $title;
  1210. // Convert all dashes/underscores into separator
  1211. $flip = $separator === '-' ? '_' : '-';
  1212. $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
  1213. // Replace dictionary words
  1214. foreach ($dictionary as $key => $value) {
  1215. $dictionary[$key] = $separator.$value.$separator;
  1216. }
  1217. $title = str_replace(array_keys($dictionary), array_values($dictionary), $title);
  1218. // Remove all characters that are not the separator, letters, numbers, or whitespace
  1219. $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));
  1220. // Replace all separator characters and whitespace by a single separator
  1221. $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
  1222. return trim($title, $separator);
  1223. }
  1224. /**
  1225. * Convert a string to snake case.
  1226. *
  1227. * @param string $value
  1228. * @param string $delimiter
  1229. * @return string
  1230. */
  1231. public static function snake($value, $delimiter = '_')
  1232. {
  1233. $key = $value;
  1234. if (isset(static::$snakeCache[$key][$delimiter])) {
  1235. return static::$snakeCache[$key][$delimiter];
  1236. }
  1237. if (! ctype_lower($value)) {
  1238. $value = preg_replace('/\s+/u', '', ucwords($value));
  1239. $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value));
  1240. }
  1241. return static::$snakeCache[$key][$delimiter] = $value;
  1242. }
  1243. /**
  1244. * Remove all whitespace from both ends of a string.
  1245. *
  1246. * @param string $value
  1247. * @param string|null $charlist
  1248. * @return string
  1249. */
  1250. public static function trim($value, $charlist = null)
  1251. {
  1252. if ($charlist === null) {
  1253. return preg_replace('~^[\s\x{FEFF}\x{200B}\x{200E}]+|[\s\x{FEFF}\x{200B}\x{200E}]+$~u', '', $value) ?? trim($value);
  1254. }
  1255. return trim($value, $charlist);
  1256. }
  1257. /**
  1258. * Remove all whitespace from the beginning of a string.
  1259. *
  1260. * @param string $value
  1261. * @param string|null $charlist
  1262. * @return string
  1263. */
  1264. public static function ltrim($value, $charlist = null)
  1265. {
  1266. if ($charlist === null) {
  1267. return preg_replace('~^[\s\x{FEFF}\x{200B}\x{200E}]+~u', '', $value) ?? ltrim($value);
  1268. }
  1269. return ltrim($value, $charlist);
  1270. }
  1271. /**
  1272. * Remove all whitespace from the end of a string.
  1273. *
  1274. * @param string $value
  1275. * @param string|null $charlist
  1276. * @return string
  1277. */
  1278. public static function rtrim($value, $charlist = null)
  1279. {
  1280. if ($charlist === null) {
  1281. return preg_replace('~[\s\x{FEFF}\x{200B}\x{200E}]+$~u', '', $value) ?? rtrim($value);
  1282. }
  1283. return rtrim($value, $charlist);
  1284. }
  1285. /**
  1286. * Remove all "extra" blank space from the given string.
  1287. *
  1288. * @param string $value
  1289. * @return string
  1290. */
  1291. public static function squish($value)
  1292. {
  1293. return preg_replace('~(\s|\x{3164}|\x{1160})+~u', ' ', static::trim($value));
  1294. }
  1295. /**
  1296. * Determine if a given string starts with a given substring.
  1297. *
  1298. * @param string $haystack
  1299. * @param string|iterable<string> $needles
  1300. * @return bool
  1301. */
  1302. public static function startsWith($haystack, $needles)
  1303. {
  1304. if (! is_iterable($needles)) {
  1305. $needles = [$needles];
  1306. }
  1307. foreach ($needles as $needle) {
  1308. if ((string) $needle !== '' && str_starts_with($haystack, $needle)) {
  1309. return true;
  1310. }
  1311. }
  1312. return false;
  1313. }
  1314. /**
  1315. * Convert a value to studly caps case.
  1316. *
  1317. * @param string $value
  1318. * @return string
  1319. */
  1320. public static function studly($value)
  1321. {
  1322. $key = $value;
  1323. if (isset(static::$studlyCache[$key])) {
  1324. return static::$studlyCache[$key];
  1325. }
  1326. $words = explode(' ', static::replace(['-', '_'], ' ', $value));
  1327. $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words);
  1328. return static::$studlyCache[$key] = implode($studlyWords);
  1329. }
  1330. /**
  1331. * Returns the portion of the string specified by the start and length parameters.
  1332. *
  1333. * @param string $string
  1334. * @param int $start
  1335. * @param int|null $length
  1336. * @param string $encoding
  1337. * @return string
  1338. */
  1339. public static function substr($string, $start, $length = null, $encoding = 'UTF-8')
  1340. {
  1341. return mb_substr($string, $start, $length, $encoding);
  1342. }
  1343. /**
  1344. * Returns the number of substring occurrences.
  1345. *
  1346. * @param string $haystack
  1347. * @param string $needle
  1348. * @param int $offset
  1349. * @param int|null $length
  1350. * @return int
  1351. */
  1352. public static function substrCount($haystack, $needle, $offset = 0, $length = null)
  1353. {
  1354. if (! is_null($length)) {
  1355. return substr_count($haystack, $needle, $offset, $length);
  1356. }
  1357. return substr_count($haystack, $needle, $offset);
  1358. }
  1359. /**
  1360. * Replace text within a portion of a string.
  1361. *
  1362. * @param string|string[] $string
  1363. * @param string|string[] $replace
  1364. * @param int|int[] $offset
  1365. * @param int|int[]|null $length
  1366. * @return string|string[]
  1367. */
  1368. public static function substrReplace($string, $replace, $offset = 0, $length = null)
  1369. {
  1370. if ($length === null) {
  1371. $length = strlen($string);
  1372. }
  1373. return substr_replace($string, $replace, $offset, $length);
  1374. }
  1375. /**
  1376. * Swap multiple keywords in a string with other keywords.
  1377. *
  1378. * @param array $map
  1379. * @param string $subject
  1380. * @return string
  1381. */
  1382. public static function swap(array $map, $subject)
  1383. {
  1384. return strtr($subject, $map);
  1385. }
  1386. /**
  1387. * Take the first or last {$limit} characters of a string.
  1388. *
  1389. * @param string $string
  1390. * @param int $limit
  1391. * @return string
  1392. */
  1393. public static function take($string, int $limit): string
  1394. {
  1395. if ($limit < 0) {
  1396. return static::substr($string, $limit);
  1397. }
  1398. return static::substr($string, 0, $limit);
  1399. }
  1400. /**
  1401. * Convert the given string to Base64 encoding.
  1402. *
  1403. * @param string $string
  1404. * @return string
  1405. */
  1406. public static function toBase64($string): string
  1407. {
  1408. return base64_encode($string);
  1409. }
  1410. /**
  1411. * Decode the given Base64 encoded string.
  1412. *
  1413. * @param string $string
  1414. * @param bool $strict
  1415. * @return string|false
  1416. */
  1417. public static function fromBase64($string, $strict = false)
  1418. {
  1419. return base64_decode($string, $strict);
  1420. }
  1421. /**
  1422. * Make a string's first character lowercase.
  1423. *
  1424. * @param string $string
  1425. * @return string
  1426. */
  1427. public static function lcfirst($string)
  1428. {
  1429. return static::lower(static::substr($string, 0, 1)).static::substr($string, 1);
  1430. }
  1431. /**
  1432. * Make a string's first character uppercase.
  1433. *
  1434. * @param string $string
  1435. * @return string
  1436. */
  1437. public static function ucfirst($string)
  1438. {
  1439. return static::upper(static::substr($string, 0, 1)).static::substr($string, 1);
  1440. }
  1441. /**
  1442. * Split a string into pieces by uppercase characters.
  1443. *
  1444. * @param string $string
  1445. * @return string[]
  1446. */
  1447. public static function ucsplit($string)
  1448. {
  1449. return preg_split('/(?=\p{Lu})/u', $string, -1, PREG_SPLIT_NO_EMPTY);
  1450. }
  1451. /**
  1452. * Get the number of words a string contains.
  1453. *
  1454. * @param string $string
  1455. * @param string|null $characters
  1456. * @return int
  1457. */
  1458. public static function wordCount($string, $characters = null)
  1459. {
  1460. return str_word_count($string, 0, $characters);
  1461. }
  1462. /**
  1463. * Wrap a string to a given number of characters.
  1464. *
  1465. * @param string $string
  1466. * @param int $characters
  1467. * @param string $break
  1468. * @param bool $cutLongWords
  1469. * @return string
  1470. */
  1471. public static function wordWrap($string, $characters = 75, $break = "\n", $cutLongWords = false)
  1472. {
  1473. return wordwrap($string, $characters, $break, $cutLongWords);
  1474. }
  1475. /**
  1476. * Generate a UUID (version 4).
  1477. *
  1478. * @return \Ramsey\Uuid\UuidInterface
  1479. */
  1480. public static function uuid()
  1481. {
  1482. return static::$uuidFactory
  1483. ? call_user_func(static::$uuidFactory)
  1484. : Uuid::uuid4();
  1485. }
  1486. /**
  1487. * Generate a time-ordered UUID.
  1488. *
  1489. * @return \Ramsey\Uuid\UuidInterface
  1490. */
  1491. public static function orderedUuid()
  1492. {
  1493. if (static::$uuidFactory) {
  1494. return call_user_func(static::$uuidFactory);
  1495. }
  1496. $factory = new UuidFactory;
  1497. $factory->setRandomGenerator(new CombGenerator(
  1498. $factory->getRandomGenerator(),
  1499. $factory->getNumberConverter()
  1500. ));
  1501. $factory->setCodec(new TimestampFirstCombCodec(
  1502. $factory->getUuidBuilder()
  1503. ));
  1504. return $factory->uuid4();
  1505. }
  1506. /**
  1507. * Set the callable that will be used to generate UUIDs.
  1508. *
  1509. * @param callable|null $factory
  1510. * @return void
  1511. */
  1512. public static function createUuidsUsing(?callable $factory = null)
  1513. {
  1514. static::$uuidFactory = $factory;
  1515. }
  1516. /**
  1517. * Set the sequence that will be used to generate UUIDs.
  1518. *
  1519. * @param array $sequence
  1520. * @param callable|null $whenMissing
  1521. * @return void
  1522. */
  1523. public static function createUuidsUsingSequence(array $sequence, $whenMissing = null)
  1524. {
  1525. $next = 0;
  1526. $whenMissing ??= function () use (&$next) {
  1527. $factoryCache = static::$uuidFactory;
  1528. static::$uuidFactory = null;
  1529. $uuid = static::uuid();
  1530. static::$uuidFactory = $factoryCache;
  1531. $next++;
  1532. return $uuid;
  1533. };
  1534. static::createUuidsUsing(function () use (&$next, $sequence, $whenMissing) {
  1535. if (array_key_exists($next, $sequence)) {
  1536. return $sequence[$next++];
  1537. }
  1538. return $whenMissing();
  1539. });
  1540. }
  1541. /**
  1542. * Always return the same UUID when generating new UUIDs.
  1543. *
  1544. * @param \Closure|null $callback
  1545. * @return \Ramsey\Uuid\UuidInterface
  1546. */
  1547. public static function freezeUuids(?Closure $callback = null)
  1548. {
  1549. $uuid = Str::uuid();
  1550. Str::createUuidsUsing(fn () => $uuid);
  1551. if ($callback !== null) {
  1552. try {
  1553. $callback($uuid);
  1554. } finally {
  1555. Str::createUuidsNormally();
  1556. }
  1557. }
  1558. return $uuid;
  1559. }
  1560. /**
  1561. * Indicate that UUIDs should be created normally and not using a custom factory.
  1562. *
  1563. * @return void
  1564. */
  1565. public static function createUuidsNormally()
  1566. {
  1567. static::$uuidFactory = null;
  1568. }
  1569. /**
  1570. * Generate a ULID.
  1571. *
  1572. * @param \DateTimeInterface|null $time
  1573. * @return \Symfony\Component\Uid\Ulid
  1574. */
  1575. public static function ulid($time = null)
  1576. {
  1577. if (static::$ulidFactory) {
  1578. return call_user_func(static::$ulidFactory);
  1579. }
  1580. if ($time === null) {
  1581. return new Ulid();
  1582. }
  1583. return new Ulid(Ulid::generate($time));
  1584. }
  1585. /**
  1586. * Indicate that ULIDs should be created normally and not using a custom factory.
  1587. *
  1588. * @return void
  1589. */
  1590. public static function createUlidsNormally()
  1591. {
  1592. static::$ulidFactory = null;
  1593. }
  1594. /**
  1595. * Set the callable that will be used to generate ULIDs.
  1596. *
  1597. * @param callable|null $factory
  1598. * @return void
  1599. */
  1600. public static function createUlidsUsing(?callable $factory = null)
  1601. {
  1602. static::$ulidFactory = $factory;
  1603. }
  1604. /**
  1605. * Set the sequence that will be used to generate ULIDs.
  1606. *
  1607. * @param array $sequence
  1608. * @param callable|null $whenMissing
  1609. * @return void
  1610. */
  1611. public static function createUlidsUsingSequence(array $sequence, $whenMissing = null)
  1612. {
  1613. $next = 0;
  1614. $whenMissing ??= function () use (&$next) {
  1615. $factoryCache = static::$ulidFactory;
  1616. static::$ulidFactory = null;
  1617. $ulid = static::ulid();
  1618. static::$ulidFactory = $factoryCache;
  1619. $next++;
  1620. return $ulid;
  1621. };
  1622. static::createUlidsUsing(function () use (&$next, $sequence, $whenMissing) {
  1623. if (array_key_exists($next, $sequence)) {
  1624. return $sequence[$next++];
  1625. }
  1626. return $whenMissing();
  1627. });
  1628. }
  1629. /**
  1630. * Always return the same ULID when generating new ULIDs.
  1631. *
  1632. * @param Closure|null $callback
  1633. * @return Ulid
  1634. */
  1635. public static function freezeUlids(?Closure $callback = null)
  1636. {
  1637. $ulid = Str::ulid();
  1638. Str::createUlidsUsing(fn () => $ulid);
  1639. if ($callback !== null) {
  1640. try {
  1641. $callback($ulid);
  1642. } finally {
  1643. Str::createUlidsNormally();
  1644. }
  1645. }
  1646. return $ulid;
  1647. }
  1648. /**
  1649. * Remove all strings from the casing caches.
  1650. *
  1651. * @return void
  1652. */
  1653. public static function flushCache()
  1654. {
  1655. static::$snakeCache = [];
  1656. static::$camelCache = [];
  1657. static::$studlyCache = [];
  1658. }
  1659. }