Str.php 53 KB

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