View file vendor/illuminate/support/Str.php

File size: 20.19Kb
  1. <?php
  2.  
  3. namespace Illuminate\Support;
  4.  
  5. use Illuminate\Support\Traits\Macroable;
  6. use League\CommonMark\GithubFlavoredMarkdownConverter;
  7. use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
  8. use Ramsey\Uuid\Generator\CombGenerator;
  9. use Ramsey\Uuid\Uuid;
  10. use Ramsey\Uuid\UuidFactory;
  11. use voku\helper\ASCII;
  12.  
  13. class Str
  14. {
  15. use Macroable;
  16.  
  17. /**
  18. * The cache of snake-cased words.
  19. *
  20. * @var array
  21. */
  22. protected static $snakeCache = [];
  23.  
  24. /**
  25. * The cache of camel-cased words.
  26. *
  27. * @var array
  28. */
  29. protected static $camelCache = [];
  30.  
  31. /**
  32. * The cache of studly-cased words.
  33. *
  34. * @var array
  35. */
  36. protected static $studlyCache = [];
  37.  
  38. /**
  39. * The callback that should be used to generate UUIDs.
  40. *
  41. * @var callable
  42. */
  43. protected static $uuidFactory;
  44.  
  45. /**
  46. * Get a new stringable object from the given string.
  47. *
  48. * @param string $string
  49. * @return \Illuminate\Support\Stringable
  50. */
  51. public static function of($string)
  52. {
  53. return new Stringable($string);
  54. }
  55.  
  56. /**
  57. * Return the remainder of a string after the first occurrence of a given value.
  58. *
  59. * @param string $subject
  60. * @param string $search
  61. * @return string
  62. */
  63. public static function after($subject, $search)
  64. {
  65. return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0];
  66. }
  67.  
  68. /**
  69. * Return the remainder of a string after the last occurrence of a given value.
  70. *
  71. * @param string $subject
  72. * @param string $search
  73. * @return string
  74. */
  75. public static function afterLast($subject, $search)
  76. {
  77. if ($search === '') {
  78. return $subject;
  79. }
  80.  
  81. $position = strrpos($subject, (string) $search);
  82.  
  83. if ($position === false) {
  84. return $subject;
  85. }
  86.  
  87. return substr($subject, $position + strlen($search));
  88. }
  89.  
  90. /**
  91. * Transliterate a UTF-8 value to ASCII.
  92. *
  93. * @param string $value
  94. * @param string $language
  95. * @return string
  96. */
  97. public static function ascii($value, $language = 'en')
  98. {
  99. return ASCII::to_ascii((string) $value, $language);
  100. }
  101.  
  102. /**
  103. * Get the portion of a string before the first occurrence of a given value.
  104. *
  105. * @param string $subject
  106. * @param string $search
  107. * @return string
  108. */
  109. public static function before($subject, $search)
  110. {
  111. if ($search === '') {
  112. return $subject;
  113. }
  114.  
  115. $result = strstr($subject, (string) $search, true);
  116.  
  117. return $result === false ? $subject : $result;
  118. }
  119.  
  120. /**
  121. * Get the portion of a string before the last occurrence of a given value.
  122. *
  123. * @param string $subject
  124. * @param string $search
  125. * @return string
  126. */
  127. public static function beforeLast($subject, $search)
  128. {
  129. if ($search === '') {
  130. return $subject;
  131. }
  132.  
  133. $pos = mb_strrpos($subject, $search);
  134.  
  135. if ($pos === false) {
  136. return $subject;
  137. }
  138.  
  139. return static::substr($subject, 0, $pos);
  140. }
  141.  
  142. /**
  143. * Get the portion of a string between two given values.
  144. *
  145. * @param string $subject
  146. * @param string $from
  147. * @param string $to
  148. * @return string
  149. */
  150. public static function between($subject, $from, $to)
  151. {
  152. if ($from === '' || $to === '') {
  153. return $subject;
  154. }
  155.  
  156. return static::beforeLast(static::after($subject, $from), $to);
  157. }
  158.  
  159. /**
  160. * Convert a value to camel case.
  161. *
  162. * @param string $value
  163. * @return string
  164. */
  165. public static function camel($value)
  166. {
  167. if (isset(static::$camelCache[$value])) {
  168. return static::$camelCache[$value];
  169. }
  170.  
  171. return static::$camelCache[$value] = lcfirst(static::studly($value));
  172. }
  173.  
  174. /**
  175. * Determine if a given string contains a given substring.
  176. *
  177. * @param string $haystack
  178. * @param string|string[] $needles
  179. * @return bool
  180. */
  181. public static function contains($haystack, $needles)
  182. {
  183. foreach ((array) $needles as $needle) {
  184. if ($needle !== '' && mb_strpos($haystack, $needle) !== false) {
  185. return true;
  186. }
  187. }
  188.  
  189. return false;
  190. }
  191.  
  192. /**
  193. * Determine if a given string contains all array values.
  194. *
  195. * @param string $haystack
  196. * @param string[] $needles
  197. * @return bool
  198. */
  199. public static function containsAll($haystack, array $needles)
  200. {
  201. foreach ($needles as $needle) {
  202. if (! static::contains($haystack, $needle)) {
  203. return false;
  204. }
  205. }
  206.  
  207. return true;
  208. }
  209.  
  210. /**
  211. * Determine if a given string ends with a given substring.
  212. *
  213. * @param string $haystack
  214. * @param string|string[] $needles
  215. * @return bool
  216. */
  217. public static function endsWith($haystack, $needles)
  218. {
  219. foreach ((array) $needles as $needle) {
  220. if ($needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle) {
  221. return true;
  222. }
  223. }
  224.  
  225. return false;
  226. }
  227.  
  228. /**
  229. * Cap a string with a single instance of a given value.
  230. *
  231. * @param string $value
  232. * @param string $cap
  233. * @return string
  234. */
  235. public static function finish($value, $cap)
  236. {
  237. $quoted = preg_quote($cap, '/');
  238.  
  239. return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap;
  240. }
  241.  
  242. /**
  243. * Determine if a given string matches a given pattern.
  244. *
  245. * @param string|array $pattern
  246. * @param string $value
  247. * @return bool
  248. */
  249. public static function is($pattern, $value)
  250. {
  251. $patterns = Arr::wrap($pattern);
  252.  
  253. if (empty($patterns)) {
  254. return false;
  255. }
  256.  
  257. foreach ($patterns as $pattern) {
  258. // If the given value is an exact match we can of course return true right
  259. // from the beginning. Otherwise, we will translate asterisks and do an
  260. // actual pattern match against the two strings to see if they match.
  261. if ($pattern == $value) {
  262. return true;
  263. }
  264.  
  265. $pattern = preg_quote($pattern, '#');
  266.  
  267. // Asterisks are translated into zero-or-more regular expression wildcards
  268. // to make it convenient to check if the strings starts with the given
  269. // pattern such as "library/*", making any string check convenient.
  270. $pattern = str_replace('\*', '.*', $pattern);
  271.  
  272. if (preg_match('#^'.$pattern.'\z#u', $value) === 1) {
  273. return true;
  274. }
  275. }
  276.  
  277. return false;
  278. }
  279.  
  280. /**
  281. * Determine if a given string is 7 bit ASCII.
  282. *
  283. * @param string $value
  284. * @return bool
  285. */
  286. public static function isAscii($value)
  287. {
  288. return ASCII::is_ascii((string) $value);
  289. }
  290.  
  291. /**
  292. * Determine if a given string is a valid UUID.
  293. *
  294. * @param string $value
  295. * @return bool
  296. */
  297. public static function isUuid($value)
  298. {
  299. if (! is_string($value)) {
  300. return false;
  301. }
  302.  
  303. return preg_match('/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iD', $value) > 0;
  304. }
  305.  
  306. /**
  307. * Convert a string to kebab case.
  308. *
  309. * @param string $value
  310. * @return string
  311. */
  312. public static function kebab($value)
  313. {
  314. return static::snake($value, '-');
  315. }
  316.  
  317. /**
  318. * Return the length of the given string.
  319. *
  320. * @param string $value
  321. * @param string|null $encoding
  322. * @return int
  323. */
  324. public static function length($value, $encoding = null)
  325. {
  326. if ($encoding) {
  327. return mb_strlen($value, $encoding);
  328. }
  329.  
  330. return mb_strlen($value);
  331. }
  332.  
  333. /**
  334. * Limit the number of characters in a string.
  335. *
  336. * @param string $value
  337. * @param int $limit
  338. * @param string $end
  339. * @return string
  340. */
  341. public static function limit($value, $limit = 100, $end = '...')
  342. {
  343. if (mb_strwidth($value, 'UTF-8') <= $limit) {
  344. return $value;
  345. }
  346.  
  347. return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
  348. }
  349.  
  350. /**
  351. * Convert the given string to lower-case.
  352. *
  353. * @param string $value
  354. * @return string
  355. */
  356. public static function lower($value)
  357. {
  358. return mb_strtolower($value, 'UTF-8');
  359. }
  360.  
  361. /**
  362. * Limit the number of words in a string.
  363. *
  364. * @param string $value
  365. * @param int $words
  366. * @param string $end
  367. * @return string
  368. */
  369. public static function words($value, $words = 100, $end = '...')
  370. {
  371. preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
  372.  
  373. if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
  374. return $value;
  375. }
  376.  
  377. return rtrim($matches[0]).$end;
  378. }
  379.  
  380. /**
  381. * Converts GitHub flavored Markdown into HTML.
  382. *
  383. * @param string $string
  384. * @param array $options
  385. * @return string
  386. */
  387. public static function markdown($string, array $options = [])
  388. {
  389. $converter = new GithubFlavoredMarkdownConverter($options);
  390.  
  391. return $converter->convertToHtml($string);
  392. }
  393.  
  394. /**
  395. * Pad both sides of a string with another.
  396. *
  397. * @param string $value
  398. * @param int $length
  399. * @param string $pad
  400. * @return string
  401. */
  402. public static function padBoth($value, $length, $pad = ' ')
  403. {
  404. return str_pad($value, $length, $pad, STR_PAD_BOTH);
  405. }
  406.  
  407. /**
  408. * Pad the left side of a string with another.
  409. *
  410. * @param string $value
  411. * @param int $length
  412. * @param string $pad
  413. * @return string
  414. */
  415. public static function padLeft($value, $length, $pad = ' ')
  416. {
  417. return str_pad($value, $length, $pad, STR_PAD_LEFT);
  418. }
  419.  
  420. /**
  421. * Pad the right side of a string with another.
  422. *
  423. * @param string $value
  424. * @param int $length
  425. * @param string $pad
  426. * @return string
  427. */
  428. public static function padRight($value, $length, $pad = ' ')
  429. {
  430. return str_pad($value, $length, $pad, STR_PAD_RIGHT);
  431. }
  432.  
  433. /**
  434. * Parse a Class[@]method style callback into class and method.
  435. *
  436. * @param string $callback
  437. * @param string|null $default
  438. * @return array<int, string|null>
  439. */
  440. public static function parseCallback($callback, $default = null)
  441. {
  442. return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default];
  443. }
  444.  
  445. /**
  446. * Get the plural form of an English word.
  447. *
  448. * @param string $value
  449. * @param int $count
  450. * @return string
  451. */
  452. public static function plural($value, $count = 2)
  453. {
  454. return Pluralizer::plural($value, $count);
  455. }
  456.  
  457. /**
  458. * Pluralize the last word of an English, studly caps case string.
  459. *
  460. * @param string $value
  461. * @param int $count
  462. * @return string
  463. */
  464. public static function pluralStudly($value, $count = 2)
  465. {
  466. $parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
  467.  
  468. $lastWord = array_pop($parts);
  469.  
  470. return implode('', $parts).self::plural($lastWord, $count);
  471. }
  472.  
  473. /**
  474. * Generate a more truly "random" alpha-numeric string.
  475. *
  476. * @param int $length
  477. * @return string
  478. */
  479. public static function random($length = 16)
  480. {
  481. $string = '';
  482.  
  483. while (($len = strlen($string)) < $length) {
  484. $size = $length - $len;
  485.  
  486. $bytes = random_bytes($size);
  487.  
  488. $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
  489. }
  490.  
  491. return $string;
  492. }
  493.  
  494. /**
  495. * Repeat the given string.
  496. *
  497. * @param string $string
  498. * @param int $times
  499. * @return string
  500. */
  501. public static function repeat(string $string, int $times)
  502. {
  503. return str_repeat($string, $times);
  504. }
  505.  
  506. /**
  507. * Replace a given value in the string sequentially with an array.
  508. *
  509. * @param string $search
  510. * @param array<int|string, string> $replace
  511. * @param string $subject
  512. * @return string
  513. */
  514. public static function replaceArray($search, array $replace, $subject)
  515. {
  516. $segments = explode($search, $subject);
  517.  
  518. $result = array_shift($segments);
  519.  
  520. foreach ($segments as $segment) {
  521. $result .= (array_shift($replace) ?? $search).$segment;
  522. }
  523.  
  524. return $result;
  525. }
  526.  
  527. /**
  528. * Replace the first occurrence of a given value in the string.
  529. *
  530. * @param string $search
  531. * @param string $replace
  532. * @param string $subject
  533. * @return string
  534. */
  535. public static function replaceFirst($search, $replace, $subject)
  536. {
  537. if ($search === '') {
  538. return $subject;
  539. }
  540.  
  541. $position = strpos($subject, $search);
  542.  
  543. if ($position !== false) {
  544. return substr_replace($subject, $replace, $position, strlen($search));
  545. }
  546.  
  547. return $subject;
  548. }
  549.  
  550. /**
  551. * Replace the last occurrence of a given value in the string.
  552. *
  553. * @param string $search
  554. * @param string $replace
  555. * @param string $subject
  556. * @return string
  557. */
  558. public static function replaceLast($search, $replace, $subject)
  559. {
  560. if ($search === '') {
  561. return $subject;
  562. }
  563.  
  564. $position = strrpos($subject, $search);
  565.  
  566. if ($position !== false) {
  567. return substr_replace($subject, $replace, $position, strlen($search));
  568. }
  569.  
  570. return $subject;
  571. }
  572.  
  573. /**
  574. * Remove any occurrence of the given string in the subject.
  575. *
  576. * @param string|array<string> $search
  577. * @param string $subject
  578. * @param bool $caseSensitive
  579. * @return string
  580. */
  581. public static function remove($search, $subject, $caseSensitive = true)
  582. {
  583. $subject = $caseSensitive
  584. ? str_replace($search, '', $subject)
  585. : str_ireplace($search, '', $subject);
  586.  
  587. return $subject;
  588. }
  589.  
  590. /**
  591. * Begin a string with a single instance of a given value.
  592. *
  593. * @param string $value
  594. * @param string $prefix
  595. * @return string
  596. */
  597. public static function start($value, $prefix)
  598. {
  599. $quoted = preg_quote($prefix, '/');
  600.  
  601. return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value);
  602. }
  603.  
  604. /**
  605. * Convert the given string to upper-case.
  606. *
  607. * @param string $value
  608. * @return string
  609. */
  610. public static function upper($value)
  611. {
  612. return mb_strtoupper($value, 'UTF-8');
  613. }
  614.  
  615. /**
  616. * Convert the given string to title case.
  617. *
  618. * @param string $value
  619. * @return string
  620. */
  621. public static function title($value)
  622. {
  623. return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
  624. }
  625.  
  626. /**
  627. * Get the singular form of an English word.
  628. *
  629. * @param string $value
  630. * @return string
  631. */
  632. public static function singular($value)
  633. {
  634. return Pluralizer::singular($value);
  635. }
  636.  
  637. /**
  638. * Generate a URL friendly "slug" from a given string.
  639. *
  640. * @param string $title
  641. * @param string $separator
  642. * @param string|null $language
  643. * @return string
  644. */
  645. public static function slug($title, $separator = '-', $language = 'en')
  646. {
  647. $title = $language ? static::ascii($title, $language) : $title;
  648.  
  649. // Convert all dashes/underscores into separator
  650. $flip = $separator === '-' ? '_' : '-';
  651.  
  652. $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
  653.  
  654. // Replace @ with the word 'at'
  655. $title = str_replace('@', $separator.'at'.$separator, $title);
  656.  
  657. // Remove all characters that are not the separator, letters, numbers, or whitespace.
  658. $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));
  659.  
  660. // Replace all separator characters and whitespace by a single separator
  661. $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
  662.  
  663. return trim($title, $separator);
  664. }
  665.  
  666. /**
  667. * Convert a string to snake case.
  668. *
  669. * @param string $value
  670. * @param string $delimiter
  671. * @return string
  672. */
  673. public static function snake($value, $delimiter = '_')
  674. {
  675. $key = $value;
  676.  
  677. if (isset(static::$snakeCache[$key][$delimiter])) {
  678. return static::$snakeCache[$key][$delimiter];
  679. }
  680.  
  681. if (! ctype_lower($value)) {
  682. $value = preg_replace('/\s+/u', '', ucwords($value));
  683.  
  684. $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value));
  685. }
  686.  
  687. return static::$snakeCache[$key][$delimiter] = $value;
  688. }
  689.  
  690. /**
  691. * Determine if a given string starts with a given substring.
  692. *
  693. * @param string $haystack
  694. * @param string|string[] $needles
  695. * @return bool
  696. */
  697. public static function startsWith($haystack, $needles)
  698. {
  699. foreach ((array) $needles as $needle) {
  700. if ((string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0) {
  701. return true;
  702. }
  703. }
  704.  
  705. return false;
  706. }
  707.  
  708. /**
  709. * Convert a value to studly caps case.
  710. *
  711. * @param string $value
  712. * @return string
  713. */
  714. public static function studly($value)
  715. {
  716. $key = $value;
  717.  
  718. if (isset(static::$studlyCache[$key])) {
  719. return static::$studlyCache[$key];
  720. }
  721.  
  722. $value = ucwords(str_replace(['-', '_'], ' ', $value));
  723.  
  724. return static::$studlyCache[$key] = str_replace(' ', '', $value);
  725. }
  726.  
  727. /**
  728. * Returns the portion of the string specified by the start and length parameters.
  729. *
  730. * @param string $string
  731. * @param int $start
  732. * @param int|null $length
  733. * @return string
  734. */
  735. public static function substr($string, $start, $length = null)
  736. {
  737. return mb_substr($string, $start, $length, 'UTF-8');
  738. }
  739.  
  740. /**
  741. * Returns the number of substring occurrences.
  742. *
  743. * @param string $haystack
  744. * @param string $needle
  745. * @param int $offset
  746. * @param int|null $length
  747. * @return int
  748. */
  749. public static function substrCount($haystack, $needle, $offset = 0, $length = null)
  750. {
  751. if (! is_null($length)) {
  752. return substr_count($haystack, $needle, $offset, $length);
  753. } else {
  754. return substr_count($haystack, $needle, $offset);
  755. }
  756. }
  757.  
  758. /**
  759. * Make a string's first character uppercase.
  760. *
  761. * @param string $string
  762. * @return string
  763. */
  764. public static function ucfirst($string)
  765. {
  766. return static::upper(static::substr($string, 0, 1)).static::substr($string, 1);
  767. }
  768.  
  769. /**
  770. * Generate a UUID (version 4).
  771. *
  772. * @return \Ramsey\Uuid\UuidInterface
  773. */
  774. public static function uuid()
  775. {
  776. return static::$uuidFactory
  777. ? call_user_func(static::$uuidFactory)
  778. : Uuid::uuid4();
  779. }
  780.  
  781. /**
  782. * Generate a time-ordered UUID (version 4).
  783. *
  784. * @return \Ramsey\Uuid\UuidInterface
  785. */
  786. public static function orderedUuid()
  787. {
  788. if (static::$uuidFactory) {
  789. return call_user_func(static::$uuidFactory);
  790. }
  791.  
  792. $factory = new UuidFactory;
  793.  
  794. $factory->setRandomGenerator(new CombGenerator(
  795. $factory->getRandomGenerator(),
  796. $factory->getNumberConverter()
  797. ));
  798.  
  799. $factory->setCodec(new TimestampFirstCombCodec(
  800. $factory->getUuidBuilder()
  801. ));
  802.  
  803. return $factory->uuid4();
  804. }
  805.  
  806. /**
  807. * Set the callable that will be used to generate UUIDs.
  808. *
  809. * @param callable|null $factory
  810. * @return void
  811. */
  812. public static function createUuidsUsing(callable $factory = null)
  813. {
  814. static::$uuidFactory = $factory;
  815. }
  816.  
  817. /**
  818. * Indicate that UUIDs should be created normally and not using a custom factory.
  819. *
  820. * @return void
  821. */
  822. public static function createUuidsNormally()
  823. {
  824. static::$uuidFactory = null;
  825. }
  826. }