PageRenderTime 58ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/danielstjules/stringy/src/Stringy.php

https://gitlab.com/Pasantias/pasantiasASLG
PHP | 1413 lines | 857 code | 135 blank | 421 comment | 51 complexity | dccf147d841ec0da658c1df6fb2d40ba MD5 | raw file
  1. <?php
  2. namespace Stringy;
  3. class Stringy implements \Countable, \IteratorAggregate, \ArrayAccess
  4. {
  5. /**
  6. * An instance's string.
  7. *
  8. * @var string
  9. */
  10. protected $str;
  11. /**
  12. * The string's encoding, which should be one of the mbstring module's
  13. * supported encodings.
  14. *
  15. * @var string
  16. */
  17. protected $encoding;
  18. /**
  19. * Initializes a Stringy object and assigns both str and encoding properties
  20. * the supplied values. $str is cast to a string prior to assignment, and if
  21. * $encoding is not specified, it defaults to mb_internal_encoding(). Throws
  22. * an InvalidArgumentException if the first argument is an array or object
  23. * without a __toString method.
  24. *
  25. * @param mixed $str Value to modify, after being cast to string
  26. * @param string $encoding The character encoding
  27. * @throws \InvalidArgumentException if an array or object without a
  28. * __toString method is passed as the first argument
  29. */
  30. public function __construct($str, $encoding = null)
  31. {
  32. if (is_array($str)) {
  33. throw new \InvalidArgumentException(
  34. 'Passed value cannot be an array'
  35. );
  36. } elseif (is_object($str) && !method_exists($str, '__toString')) {
  37. throw new \InvalidArgumentException(
  38. 'Passed object must have a __toString method'
  39. );
  40. }
  41. $this->str = (string) $str;
  42. $this->encoding = $encoding ?: mb_internal_encoding();
  43. }
  44. /**
  45. * Creates a Stringy object and assigns both str and encoding properties
  46. * the supplied values. $str is cast to a string prior to assignment, and if
  47. * $encoding is not specified, it defaults to mb_internal_encoding(). It
  48. * then returns the initialized object. Throws an InvalidArgumentException
  49. * if the first argument is an array or object without a __toString method.
  50. *
  51. * @param mixed $str Value to modify, after being cast to string
  52. * @param string $encoding The character encoding
  53. * @return Stringy A Stringy object
  54. * @throws \InvalidArgumentException if an array or object without a
  55. * __toString method is passed as the first argument
  56. */
  57. public static function create($str, $encoding = null)
  58. {
  59. return new static($str, $encoding);
  60. }
  61. /**
  62. * Returns the value in $str.
  63. *
  64. * @return string The current value of the $str property
  65. */
  66. public function __toString()
  67. {
  68. return $this->str;
  69. }
  70. /**
  71. * Returns the encoding used by the Stringy object.
  72. *
  73. * @return string The current value of the $encoding property
  74. */
  75. public function getEncoding()
  76. {
  77. return $this->encoding;
  78. }
  79. /**
  80. * Returns the length of the string, implementing the countable interface.
  81. *
  82. * @return int The number of characters in the string, given the encoding
  83. */
  84. public function count()
  85. {
  86. return $this->length();
  87. }
  88. /**
  89. * Returns a new ArrayIterator, thus implementing the IteratorAggregate
  90. * interface. The ArrayIterator's constructor is passed an array of chars
  91. * in the multibyte string. This enables the use of foreach with instances
  92. * of Stringy\Stringy.
  93. *
  94. * @return \ArrayIterator An iterator for the characters in the string
  95. */
  96. public function getIterator()
  97. {
  98. return new \ArrayIterator($this->chars());
  99. }
  100. /**
  101. * Returns whether or not a character exists at an index. Offsets may be
  102. * negative to count from the last character in the string. Implements
  103. * part of the ArrayAccess interface.
  104. *
  105. * @param mixed $offset The index to check
  106. * @return boolean Whether or not the index exists
  107. */
  108. public function offsetExists($offset)
  109. {
  110. $length = $this->length();
  111. $offset = (int) $offset;
  112. if ($offset >= 0) {
  113. return ($length > $offset);
  114. }
  115. return ($length >= abs($offset));
  116. }
  117. /**
  118. * Returns the character at the given index. Offsets may be negative to
  119. * count from the last character in the string. Implements part of the
  120. * ArrayAccess interface, and throws an OutOfBoundsException if the index
  121. * does not exist.
  122. *
  123. * @param mixed $offset The index from which to retrieve the char
  124. * @return mixed The character at the specified index
  125. * @throws \OutOfBoundsException If the positive or negative offset does
  126. * not exist
  127. */
  128. public function offsetGet($offset)
  129. {
  130. $offset = (int) $offset;
  131. $length = $this->length();
  132. if (($offset >= 0 && $length <= $offset) || $length < abs($offset)) {
  133. throw new \OutOfBoundsException('No character exists at the index');
  134. }
  135. return mb_substr($this->str, $offset, 1, $this->encoding);
  136. }
  137. /**
  138. * Implements part of the ArrayAccess interface, but throws an exception
  139. * when called. This maintains the immutability of Stringy objects.
  140. *
  141. * @param mixed $offset The index of the character
  142. * @param mixed $value Value to set
  143. * @throws \Exception When called
  144. */
  145. public function offsetSet($offset, $value)
  146. {
  147. // Stringy is immutable, cannot directly set char
  148. throw new \Exception('Stringy object is immutable, cannot modify char');
  149. }
  150. /**
  151. * Implements part of the ArrayAccess interface, but throws an exception
  152. * when called. This maintains the immutability of Stringy objects.
  153. *
  154. * @param mixed $offset The index of the character
  155. * @throws \Exception When called
  156. */
  157. public function offsetUnset($offset)
  158. {
  159. // Don't allow directly modifying the string
  160. throw new \Exception('Stringy object is immutable, cannot unset char');
  161. }
  162. /**
  163. * Returns an array consisting of the characters in the string.
  164. *
  165. * @return array An array of string chars
  166. */
  167. public function chars()
  168. {
  169. $chars = array();
  170. for ($i = 0, $l = $this->length(); $i < $l; $i++) {
  171. $chars[] = $this->at($i)->str;
  172. }
  173. return $chars;
  174. }
  175. /**
  176. * Converts the first character of the supplied string to upper case.
  177. *
  178. * @return Stringy Object with the first character of $str being upper case
  179. */
  180. public function upperCaseFirst()
  181. {
  182. $first = mb_substr($this->str, 0, 1, $this->encoding);
  183. $rest = mb_substr($this->str, 1, $this->length() - 1,
  184. $this->encoding);
  185. $str = mb_strtoupper($first, $this->encoding) . $rest;
  186. return static::create($str, $this->encoding);
  187. }
  188. /**
  189. * Converts the first character of the string to lower case.
  190. *
  191. * @return Stringy Object with the first character of $str being lower case
  192. */
  193. public function lowerCaseFirst()
  194. {
  195. $first = mb_substr($this->str, 0, 1, $this->encoding);
  196. $rest = mb_substr($this->str, 1, $this->length() - 1,
  197. $this->encoding);
  198. $str = mb_strtolower($first, $this->encoding) . $rest;
  199. return static::create($str, $this->encoding);
  200. }
  201. /**
  202. * Returns a camelCase version of the string. Trims surrounding spaces,
  203. * capitalizes letters following digits, spaces, dashes and underscores,
  204. * and removes spaces, dashes, as well as underscores.
  205. *
  206. * @return Stringy Object with $str in camelCase
  207. */
  208. public function camelize()
  209. {
  210. $encoding = $this->encoding;
  211. $stringy = $this->trim()->lowerCaseFirst();
  212. $camelCase = preg_replace_callback(
  213. '/[-_\s]+(.)?/u',
  214. function ($match) use ($encoding) {
  215. return $match[1] ? mb_strtoupper($match[1], $encoding) : '';
  216. },
  217. $stringy->str
  218. );
  219. $stringy->str = preg_replace_callback(
  220. '/[\d]+(.)?/u',
  221. function ($match) use ($encoding) {
  222. return mb_strtoupper($match[0], $encoding);
  223. },
  224. $camelCase
  225. );
  226. return $stringy;
  227. }
  228. /**
  229. * Returns an UpperCamelCase version of the supplied string. It trims
  230. * surrounding spaces, capitalizes letters following digits, spaces, dashes
  231. * and underscores, and removes spaces, dashes, underscores.
  232. *
  233. * @return Stringy Object with $str in UpperCamelCase
  234. */
  235. public function upperCamelize()
  236. {
  237. return $this->camelize()->upperCaseFirst();
  238. }
  239. /**
  240. * Returns a lowercase and trimmed string separated by dashes. Dashes are
  241. * inserted before uppercase characters (with the exception of the first
  242. * character of the string), and in place of spaces as well as underscores.
  243. *
  244. * @return Stringy Object with a dasherized $str
  245. */
  246. public function dasherize()
  247. {
  248. return $this->delimit('-');
  249. }
  250. /**
  251. * Returns a lowercase and trimmed string separated by underscores.
  252. * Underscores are inserted before uppercase characters (with the exception
  253. * of the first character of the string), and in place of spaces as well as
  254. * dashes.
  255. *
  256. * @return Stringy Object with an underscored $str
  257. */
  258. public function underscored()
  259. {
  260. return $this->delimit('_');
  261. }
  262. /**
  263. * Returns a lowercase and trimmed string separated by the given delimiter.
  264. * Delimiters are inserted before uppercase characters (with the exception
  265. * of the first character of the string), and in place of spaces, dashes,
  266. * and underscores. Alpha delimiters are not converted to lowercase.
  267. *
  268. * @param string $delimiter Sequence used to separate parts of the string
  269. * @return Stringy Object with a delimited $str
  270. */
  271. public function delimit($delimiter)
  272. {
  273. // Save current regex encoding so we can reset it after
  274. $regexEncoding = mb_regex_encoding();
  275. mb_regex_encoding($this->encoding);
  276. $str = mb_ereg_replace('\B([A-Z])', '-\1', $this->trim());
  277. $str = mb_strtolower($str, $this->encoding);
  278. $str = mb_ereg_replace('[-_\s]+', $delimiter, $str);
  279. mb_regex_encoding($regexEncoding);
  280. return static::create($str, $this->encoding);
  281. }
  282. /**
  283. * Returns a case swapped version of the string.
  284. *
  285. * @return Stringy Object whose $str has each character's case swapped
  286. */
  287. public function swapCase()
  288. {
  289. $stringy = static::create($this->str, $this->encoding);
  290. $encoding = $stringy->encoding;
  291. $stringy->str = preg_replace_callback(
  292. '/[\S]/u',
  293. function ($match) use ($encoding) {
  294. if ($match[0] == mb_strtoupper($match[0], $encoding)) {
  295. return mb_strtolower($match[0], $encoding);
  296. } else {
  297. return mb_strtoupper($match[0], $encoding);
  298. }
  299. },
  300. $stringy->str
  301. );
  302. return $stringy;
  303. }
  304. /**
  305. * Returns a trimmed string with the first letter of each word capitalized.
  306. * Ignores the case of other letters, preserving any acronyms. Also accepts
  307. * an array, $ignore, allowing you to list words not to be capitalized.
  308. *
  309. * @param array $ignore An array of words not to capitalize
  310. * @return Stringy Object with a titleized $str
  311. */
  312. public function titleize($ignore = null)
  313. {
  314. $buffer = $this->trim();
  315. $encoding = $this->encoding;
  316. $buffer = preg_replace_callback(
  317. '/([\S]+)/u',
  318. function ($match) use ($encoding, $ignore) {
  319. if ($ignore && in_array($match[0], $ignore)) {
  320. return $match[0];
  321. } else {
  322. $stringy = new Stringy($match[0], $encoding);
  323. return (string) $stringy->upperCaseFirst();
  324. }
  325. },
  326. $buffer
  327. );
  328. return new Stringy($buffer, $encoding);
  329. }
  330. /**
  331. * Capitalizes the first word of the string, replaces underscores with
  332. * spaces, and strips '_id'.
  333. *
  334. * @return Stringy Object with a humanized $str
  335. */
  336. public function humanize()
  337. {
  338. $str = str_replace(array('_id', '_'), array('', ' '), $this->str);
  339. return static::create($str, $this->encoding)->trim()->upperCaseFirst();
  340. }
  341. /**
  342. * Returns a string with smart quotes, ellipsis characters, and dashes from
  343. * Windows-1252 (commonly used in Word documents) replaced by their ASCII
  344. * equivalents.
  345. *
  346. * @return Stringy Object whose $str has those characters removed
  347. */
  348. public function tidy()
  349. {
  350. $str = preg_replace(array(
  351. '/\x{2026}/u',
  352. '/[\x{201C}\x{201D}]/u',
  353. '/[\x{2018}\x{2019}]/u',
  354. '/[\x{2013}\x{2014}]/u',
  355. ), array(
  356. '...',
  357. '"',
  358. "'",
  359. '-',
  360. ), $this->str);
  361. return static::create($str, $this->encoding);
  362. }
  363. /**
  364. * Trims the string and replaces consecutive whitespace characters with a
  365. * single space. This includes tabs and newline characters, as well as
  366. * multibyte whitespace such as the thin space and ideographic space.
  367. *
  368. * @return Stringy Object with a trimmed $str and condensed whitespace
  369. */
  370. public function collapseWhitespace()
  371. {
  372. return $this->regexReplace('[[:space:]]+', ' ')->trim();
  373. }
  374. /**
  375. * Returns an ASCII version of the string. A set of non-ASCII characters are
  376. * replaced with their closest ASCII counterparts, and the rest are removed
  377. * unless instructed otherwise.
  378. *
  379. * @param bool $removeUnsupported Whether or not to remove the
  380. * unsupported characters
  381. * @return Stringy Object whose $str contains only ASCII characters
  382. */
  383. public function toAscii($removeUnsupported = true)
  384. {
  385. $str = $this->str;
  386. foreach ($this->charsArray() as $key => $value) {
  387. $str = str_replace($value, $key, $str);
  388. }
  389. if ($removeUnsupported) {
  390. $str = preg_replace('/[^\x20-\x7E]/u', '', $str);
  391. }
  392. return static::create($str, $this->encoding);
  393. }
  394. /**
  395. * Returns the replacements for the toAscii() method.
  396. *
  397. * @return array An array of replacements.
  398. */
  399. protected function charsArray()
  400. {
  401. static $charsArray;
  402. if (isset($charsArray)) return $charsArray;
  403. return $charsArray = array(
  404. 'a' => array(
  405. 'à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ',
  406. 'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ä', 'ā', 'ą',
  407. 'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ',
  408. 'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ',
  409. 'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ'),
  410. 'b' => array('б', 'β', 'Ъ', 'Ь', 'ب'),
  411. 'c' => array('ç', 'ć', 'č', 'ĉ', 'ċ'),
  412. 'd' => array('ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ',
  413. 'д', 'δ', 'د', 'ض'),
  414. 'e' => array('é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ',
  415. 'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ',
  416. 'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э',
  417. 'є', 'ə'),
  418. 'f' => array('ф', 'φ', 'ف'),
  419. 'g' => array('ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ج'),
  420. 'h' => array('ĥ', 'ħ', 'η', 'ή', 'ح', 'ه'),
  421. 'i' => array('í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į',
  422. 'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ',
  423. 'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ',
  424. 'ῗ', 'і', 'ї', 'и'),
  425. 'j' => array('ĵ', 'ј', 'Ј'),
  426. 'k' => array('ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك'),
  427. 'l' => array('ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل'),
  428. 'm' => array('м', 'μ', 'م'),
  429. 'n' => array('ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن'),
  430. 'o' => array('ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ',
  431. 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő',
  432. 'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό',
  433. 'ö', 'о', 'و', 'θ'),
  434. 'p' => array('п', 'π'),
  435. 'r' => array('ŕ', 'ř', 'ŗ', 'р', 'ρ', 'ر'),
  436. 's' => array('ś', 'š', 'ş', 'с', 'σ', 'ș', 'ς', 'س', 'ص'),
  437. 't' => array('ť', 'ţ', 'т', 'τ', 'ț', 'ت', 'ط'),
  438. 'u' => array('ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ',
  439. 'ự', 'ü', 'û', 'ū', 'ů', 'ű', 'ŭ', 'ų', 'µ', 'у'),
  440. 'v' => array('в'),
  441. 'w' => array('ŵ', 'ω', 'ώ'),
  442. 'x' => array('χ'),
  443. 'y' => array('ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'ÿ', 'ŷ', 'й', 'ы', 'υ',
  444. 'ϋ', 'ύ', 'ΰ', 'ي'),
  445. 'z' => array('ź', 'ž', 'ż', 'з', 'ζ', 'ز'),
  446. 'aa' => array('ع'),
  447. 'ae' => array('æ'),
  448. 'ch' => array('ч'),
  449. 'dj' => array('ђ', 'đ'),
  450. 'dz' => array('џ'),
  451. 'gh' => array('غ'),
  452. 'kh' => array('х', 'خ'),
  453. 'lj' => array('љ'),
  454. 'nj' => array('њ'),
  455. 'oe' => array('œ'),
  456. 'ps' => array('ψ'),
  457. 'sh' => array('ш'),
  458. 'shch' => array('щ'),
  459. 'ss' => array('ß'),
  460. 'th' => array('þ', 'ث', 'ذ', 'ظ'),
  461. 'ts' => array('ц'),
  462. 'ya' => array('я'),
  463. 'yu' => array('ю'),
  464. 'zh' => array('ж'),
  465. '(c)' => array('©'),
  466. 'A' => array('Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ',
  467. 'Ặ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Ä', 'Å', 'Ā',
  468. 'Ą', 'Α', 'Ά', 'Ἀ', 'Ἁ', 'Ἂ', 'Ἃ', 'Ἄ', 'Ἅ', 'Ἆ',
  469. 'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ',
  470. 'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А'),
  471. 'B' => array('Б', 'Β'),
  472. 'C' => array('Ç','Ć', 'Č', 'Ĉ', 'Ċ'),
  473. 'D' => array('Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ'),
  474. 'E' => array('É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ',
  475. 'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ',
  476. 'Ἑ', 'Ἒ', 'Ἓ', 'Ἔ', 'Ἕ', 'Έ', 'Ὲ', 'Е', 'Ё', 'Э',
  477. 'Є', 'Ə'),
  478. 'F' => array('Ф', 'Φ'),
  479. 'G' => array('Ğ', 'Ġ', 'Ģ', 'Г', 'Ґ', 'Γ'),
  480. 'H' => array('Η', 'Ή'),
  481. 'I' => array('Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'Î', 'Ï', 'Ī', 'Ĭ', 'Į',
  482. 'İ', 'Ι', 'Ί', 'Ϊ', 'Ἰ', 'Ἱ', 'Ἳ', 'Ἴ', 'Ἵ', 'Ἶ',
  483. 'Ἷ', 'Ῐ', 'Ῑ', 'Ὶ', 'Ί', 'И', 'І', 'Ї'),
  484. 'K' => array('К', 'Κ'),
  485. 'L' => array('Ĺ', 'Ł', 'Л', 'Λ', 'Ļ'),
  486. 'M' => array('М', 'Μ'),
  487. 'N' => array('Ń', 'Ñ', 'Ň', 'Ņ', 'Ŋ', 'Н', 'Ν'),
  488. 'O' => array('Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ',
  489. 'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'Ö', 'Ø', 'Ō',
  490. 'Ő', 'Ŏ', 'Ο', 'Ό', 'Ὀ', 'Ὁ', 'Ὂ', 'Ὃ', 'Ὄ', 'Ὅ',
  491. 'Ὸ', 'Ό', 'О', 'Θ', 'Ө'),
  492. 'P' => array('П', 'Π'),
  493. 'R' => array('Ř', 'Ŕ', 'Р', 'Ρ'),
  494. 'S' => array('Ş', 'Ŝ', 'Ș', 'Š', 'Ś', 'С', 'Σ'),
  495. 'T' => array('Ť', 'Ţ', 'Ŧ', 'Ț', 'Т', 'Τ'),
  496. 'U' => array('Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ',
  497. 'Ự', 'Û', 'Ü', 'Ū', 'Ů', 'Ű', 'Ŭ', 'Ų', 'У'),
  498. 'V' => array('В'),
  499. 'W' => array('Ω', 'Ώ'),
  500. 'X' => array('Χ'),
  501. 'Y' => array('Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Ÿ', 'Ῠ', 'Ῡ', 'Ὺ', 'Ύ',
  502. 'Ы', 'Й', 'Υ', 'Ϋ'),
  503. 'Z' => array('Ź', 'Ž', 'Ż', 'З', 'Ζ'),
  504. 'AE' => array('Æ'),
  505. 'CH' => array('Ч'),
  506. 'DJ' => array('Ђ'),
  507. 'DZ' => array('Џ'),
  508. 'KH' => array('Х'),
  509. 'LJ' => array('Љ'),
  510. 'NJ' => array('Њ'),
  511. 'PS' => array('Ψ'),
  512. 'SH' => array('Ш'),
  513. 'SHCH' => array('Щ'),
  514. 'SS' => array('ẞ'),
  515. 'TH' => array('Þ'),
  516. 'TS' => array('Ц'),
  517. 'YA' => array('Я'),
  518. 'YU' => array('Ю'),
  519. 'ZH' => array('Ж'),
  520. ' ' => array("\xC2\xA0", "\xE2\x80\x80", "\xE2\x80\x81",
  521. "\xE2\x80\x82", "\xE2\x80\x83", "\xE2\x80\x84",
  522. "\xE2\x80\x85", "\xE2\x80\x86", "\xE2\x80\x87",
  523. "\xE2\x80\x88", "\xE2\x80\x89", "\xE2\x80\x8A",
  524. "\xE2\x80\xAF", "\xE2\x81\x9F", "\xE3\x80\x80"),
  525. );
  526. }
  527. /**
  528. * Pads the string to a given length with $padStr. If length is less than
  529. * or equal to the length of the string, no padding takes places. The
  530. * default string used for padding is a space, and the default type (one of
  531. * 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException
  532. * if $padType isn't one of those 3 values.
  533. *
  534. * @param int $length Desired string length after padding
  535. * @param string $padStr String used to pad, defaults to space
  536. * @param string $padType One of 'left', 'right', 'both'
  537. * @return Stringy Object with a padded $str
  538. * @throws InvalidArgumentException If $padType isn't one of 'right',
  539. * 'left' or 'both'
  540. */
  541. public function pad($length, $padStr = ' ', $padType = 'right')
  542. {
  543. if (!in_array($padType, array('left', 'right', 'both'))) {
  544. throw new \InvalidArgumentException('Pad expects $padType ' .
  545. "to be one of 'left', 'right' or 'both'");
  546. }
  547. switch ($padType) {
  548. case 'left':
  549. return $this->padLeft($length, $padStr);
  550. case 'right':
  551. return $this->padRight($length, $padStr);
  552. default:
  553. return $this->padBoth($length, $padStr);
  554. }
  555. }
  556. /**
  557. * Returns a new string of a given length such that the beginning of the
  558. * string is padded. Alias for pad() with a $padType of 'left'.
  559. *
  560. * @param int $length Desired string length after padding
  561. * @param string $padStr String used to pad, defaults to space
  562. * @return Stringy String with left padding
  563. */
  564. public function padLeft($length, $padStr = ' ')
  565. {
  566. return $this->applyPadding($length - $this->length(), 0, $padStr);
  567. }
  568. /**
  569. * Returns a new string of a given length such that the end of the string
  570. * is padded. Alias for pad() with a $padType of 'right'.
  571. *
  572. * @param int $length Desired string length after padding
  573. * @param string $padStr String used to pad, defaults to space
  574. * @return Stringy String with right padding
  575. */
  576. public function padRight($length, $padStr = ' ')
  577. {
  578. return $this->applyPadding(0, $length - $this->length(), $padStr);
  579. }
  580. /**
  581. * Returns a new string of a given length such that both sides of the
  582. * string are padded. Alias for pad() with a $padType of 'both'.
  583. *
  584. * @param int $length Desired string length after padding
  585. * @param string $padStr String used to pad, defaults to space
  586. * @return Stringy String with padding applied
  587. */
  588. public function padBoth($length, $padStr = ' ')
  589. {
  590. $padding = $length - $this->length();
  591. return $this->applyPadding(floor($padding / 2), ceil($padding / 2),
  592. $padStr);
  593. }
  594. /**
  595. * Adds the specified amount of left and right padding to the given string.
  596. * The default character used is a space.
  597. *
  598. * @param int $left Length of left padding
  599. * @param int $right Length of right padding
  600. * @param string $padStr String used to pad
  601. * @return Stringy String with padding applied
  602. */
  603. private function applyPadding($left = 0, $right = 0, $padStr = ' ')
  604. {
  605. $stringy = static::create($this->str, $this->encoding);
  606. $length = mb_strlen($padStr, $stringy->encoding);
  607. $strLength = $stringy->length();
  608. $paddedLength = $strLength + $left + $right;
  609. if (!$length || $paddedLength <= $strLength) {
  610. return $stringy;
  611. }
  612. $leftPadding = mb_substr(str_repeat($padStr, ceil($left / $length)), 0,
  613. $left, $stringy->encoding);
  614. $rightPadding = mb_substr(str_repeat($padStr, ceil($right / $length)),
  615. 0, $right, $stringy->encoding);
  616. $stringy->str = $leftPadding . $stringy->str . $rightPadding;
  617. return $stringy;
  618. }
  619. /**
  620. * Returns true if the string begins with $substring, false otherwise. By
  621. * default, the comparison is case-sensitive, but can be made insensitive
  622. * by setting $caseSensitive to false.
  623. *
  624. * @param string $substring The substring to look for
  625. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  626. * @return bool Whether or not $str starts with $substring
  627. */
  628. public function startsWith($substring, $caseSensitive = true)
  629. {
  630. $substringLength = mb_strlen($substring, $this->encoding);
  631. $startOfStr = mb_substr($this->str, 0, $substringLength,
  632. $this->encoding);
  633. if (!$caseSensitive) {
  634. $substring = mb_strtolower($substring, $this->encoding);
  635. $startOfStr = mb_strtolower($startOfStr, $this->encoding);
  636. }
  637. return (string) $substring === $startOfStr;
  638. }
  639. /**
  640. * Returns true if the string ends with $substring, false otherwise. By
  641. * default, the comparison is case-sensitive, but can be made insensitive
  642. * by setting $caseSensitive to false.
  643. *
  644. * @param string $substring The substring to look for
  645. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  646. * @return bool Whether or not $str ends with $substring
  647. */
  648. public function endsWith($substring, $caseSensitive = true)
  649. {
  650. $substringLength = mb_strlen($substring, $this->encoding);
  651. $strLength = $this->length();
  652. $endOfStr = mb_substr($this->str, $strLength - $substringLength,
  653. $substringLength, $this->encoding);
  654. if (!$caseSensitive) {
  655. $substring = mb_strtolower($substring, $this->encoding);
  656. $endOfStr = mb_strtolower($endOfStr, $this->encoding);
  657. }
  658. return (string) $substring === $endOfStr;
  659. }
  660. /**
  661. * Converts each tab in the string to some number of spaces, as defined by
  662. * $tabLength. By default, each tab is converted to 4 consecutive spaces.
  663. *
  664. * @param int $tabLength Number of spaces to replace each tab with
  665. * @return Stringy Object whose $str has had tabs switched to spaces
  666. */
  667. public function toSpaces($tabLength = 4)
  668. {
  669. $spaces = str_repeat(' ', $tabLength);
  670. $str = str_replace("\t", $spaces, $this->str);
  671. return static::create($str, $this->encoding);
  672. }
  673. /**
  674. * Converts each occurrence of some consecutive number of spaces, as
  675. * defined by $tabLength, to a tab. By default, each 4 consecutive spaces
  676. * are converted to a tab.
  677. *
  678. * @param int $tabLength Number of spaces to replace with a tab
  679. * @return Stringy Object whose $str has had spaces switched to tabs
  680. */
  681. public function toTabs($tabLength = 4)
  682. {
  683. $spaces = str_repeat(' ', $tabLength);
  684. $str = str_replace($spaces, "\t", $this->str);
  685. return static::create($str, $this->encoding);
  686. }
  687. /**
  688. * Converts the first character of each word in the string to uppercase.
  689. *
  690. * @return Stringy Object with all characters of $str being title-cased
  691. */
  692. public function toTitleCase()
  693. {
  694. $str = mb_convert_case($this->str, MB_CASE_TITLE, $this->encoding);
  695. return static::create($str, $this->encoding);
  696. }
  697. /**
  698. * Converts all characters in the string to lowercase. An alias for PHP's
  699. * mb_strtolower().
  700. *
  701. * @return Stringy Object with all characters of $str being lowercase
  702. */
  703. public function toLowerCase()
  704. {
  705. $str = mb_strtolower($this->str, $this->encoding);
  706. return static::create($str, $this->encoding);
  707. }
  708. /**
  709. * Converts all characters in the string to uppercase. An alias for PHP's
  710. * mb_strtoupper().
  711. *
  712. * @return Stringy Object with all characters of $str being uppercase
  713. */
  714. public function toUpperCase()
  715. {
  716. $str = mb_strtoupper($this->str, $this->encoding);
  717. return static::create($str, $this->encoding);
  718. }
  719. /**
  720. * Converts the string into an URL slug. This includes replacing non-ASCII
  721. * characters with their closest ASCII equivalents, removing remaining
  722. * non-ASCII and non-alphanumeric characters, and replacing whitespace with
  723. * $replacement. The replacement defaults to a single dash, and the string
  724. * is also converted to lowercase.
  725. *
  726. * @param string $replacement The string used to replace whitespace
  727. * @return Stringy Object whose $str has been converted to an URL slug
  728. */
  729. public function slugify($replacement = '-')
  730. {
  731. $stringy = $this->toAscii();
  732. $quotedReplacement = preg_quote($replacement);
  733. $pattern = "/[^a-zA-Z\d\s-_$quotedReplacement]/u";
  734. $stringy->str = preg_replace($pattern, '', $stringy);
  735. return $stringy->toLowerCase()->delimit($replacement)
  736. ->removeLeft($replacement)->removeRight($replacement);
  737. }
  738. /**
  739. * Returns true if the string contains $needle, false otherwise. By default
  740. * the comparison is case-sensitive, but can be made insensitive by setting
  741. * $caseSensitive to false.
  742. *
  743. * @param string $needle Substring to look for
  744. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  745. * @return bool Whether or not $str contains $needle
  746. */
  747. public function contains($needle, $caseSensitive = true)
  748. {
  749. $encoding = $this->encoding;
  750. if ($caseSensitive) {
  751. return (mb_strpos($this->str, $needle, 0, $encoding) !== false);
  752. } else {
  753. return (mb_stripos($this->str, $needle, 0, $encoding) !== false);
  754. }
  755. }
  756. /**
  757. * Returns true if the string contains any $needles, false otherwise. By
  758. * default the comparison is case-sensitive, but can be made insensitive by
  759. * setting $caseSensitive to false.
  760. *
  761. * @param array $needles Substrings to look for
  762. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  763. * @return bool Whether or not $str contains $needle
  764. */
  765. public function containsAny($needles, $caseSensitive = true)
  766. {
  767. if (empty($needles)) {
  768. return false;
  769. }
  770. foreach ($needles as $needle) {
  771. if ($this->contains($needle, $caseSensitive)) {
  772. return true;
  773. }
  774. }
  775. return false;
  776. }
  777. /**
  778. * Returns true if the string contains all $needles, false otherwise. By
  779. * default the comparison is case-sensitive, but can be made insensitive by
  780. * setting $caseSensitive to false.
  781. *
  782. * @param array $needles Substrings to look for
  783. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  784. * @return bool Whether or not $str contains $needle
  785. */
  786. public function containsAll($needles, $caseSensitive = true)
  787. {
  788. if (empty($needles)) {
  789. return false;
  790. }
  791. foreach ($needles as $needle) {
  792. if (!$this->contains($needle, $caseSensitive)) {
  793. return false;
  794. }
  795. }
  796. return true;
  797. }
  798. /**
  799. * Returns the index of the first occurrence of $needle in the string,
  800. * and false if not found. Accepts an optional offset from which to begin
  801. * the search.
  802. *
  803. * @param string $needle Substring to look for
  804. * @param int $offset Offset from which to search
  805. * @return int|bool The occurrence's index if found, otherwise false
  806. */
  807. public function indexOf($needle, $offset = 0)
  808. {
  809. return mb_strpos($this->str, (string) $needle,
  810. (int) $offset, $this->encoding);
  811. }
  812. /**
  813. * Returns the index of the last occurrence of $needle in the string,
  814. * and false if not found. Accepts an optional offset from which to begin
  815. * the search.
  816. *
  817. * @param string $needle Substring to look for
  818. * @param int $offset Offset from which to search
  819. * @return int|bool The last occurrence's index if found, otherwise false
  820. */
  821. public function indexOfLast($needle, $offset = 0)
  822. {
  823. return mb_strrpos($this->str, (string) $needle,
  824. (int) $offset, $this->encoding);
  825. }
  826. /**
  827. * Surrounds $str with the given substring.
  828. *
  829. * @param string $substring The substring to add to both sides
  830. * @return Stringy Object whose $str had the substring both prepended and
  831. * appended
  832. */
  833. public function surround($substring)
  834. {
  835. $str = implode('', array($substring, $this->str, $substring));
  836. return static::create($str, $this->encoding);
  837. }
  838. /**
  839. * Inserts $substring into the string at the $index provided.
  840. *
  841. * @param string $substring String to be inserted
  842. * @param int $index The index at which to insert the substring
  843. * @return Stringy Object with the resulting $str after the insertion
  844. */
  845. public function insert($substring, $index)
  846. {
  847. $stringy = static::create($this->str, $this->encoding);
  848. if ($index > $stringy->length()) {
  849. return $stringy;
  850. }
  851. $start = mb_substr($stringy->str, 0, $index, $stringy->encoding);
  852. $end = mb_substr($stringy->str, $index, $stringy->length(),
  853. $stringy->encoding);
  854. $stringy->str = $start . $substring . $end;
  855. return $stringy;
  856. }
  857. /**
  858. * Truncates the string to a given length. If $substring is provided, and
  859. * truncating occurs, the string is further truncated so that the substring
  860. * may be appended without exceeding the desired length.
  861. *
  862. * @param int $length Desired length of the truncated string
  863. * @param string $substring The substring to append if it can fit
  864. * @return Stringy Object with the resulting $str after truncating
  865. */
  866. public function truncate($length, $substring = '')
  867. {
  868. $stringy = static::create($this->str, $this->encoding);
  869. if ($length >= $stringy->length()) {
  870. return $stringy;
  871. }
  872. // Need to further trim the string so we can append the substring
  873. $substringLength = mb_strlen($substring, $stringy->encoding);
  874. $length = $length - $substringLength;
  875. $truncated = mb_substr($stringy->str, 0, $length, $stringy->encoding);
  876. $stringy->str = $truncated . $substring;
  877. return $stringy;
  878. }
  879. /**
  880. * Truncates the string to a given length, while ensuring that it does not
  881. * split words. If $substring is provided, and truncating occurs, the
  882. * string is further truncated so that the substring may be appended without
  883. * exceeding the desired length.
  884. *
  885. * @param int $length Desired length of the truncated string
  886. * @param string $substring The substring to append if it can fit
  887. * @return Stringy Object with the resulting $str after truncating
  888. */
  889. public function safeTruncate($length, $substring = '')
  890. {
  891. $stringy = static::create($this->str, $this->encoding);
  892. if ($length >= $stringy->length()) {
  893. return $stringy;
  894. }
  895. // Need to further trim the string so we can append the substring
  896. $encoding = $stringy->encoding;
  897. $substringLength = mb_strlen($substring, $encoding);
  898. $length = $length - $substringLength;
  899. $truncated = mb_substr($stringy->str, 0, $length, $encoding);
  900. // If the last word was truncated
  901. if (mb_strpos($stringy->str, ' ', $length - 1, $encoding) != $length) {
  902. // Find pos of the last occurrence of a space, get up to that
  903. $lastPos = mb_strrpos($truncated, ' ', 0, $encoding);
  904. $truncated = mb_substr($truncated, 0, $lastPos, $encoding);
  905. }
  906. $stringy->str = $truncated . $substring;
  907. return $stringy;
  908. }
  909. /**
  910. * Returns a reversed string. A multibyte version of strrev().
  911. *
  912. * @return Stringy Object with a reversed $str
  913. */
  914. public function reverse()
  915. {
  916. $strLength = $this->length();
  917. $reversed = '';
  918. // Loop from last index of string to first
  919. for ($i = $strLength - 1; $i >= 0; $i--) {
  920. $reversed .= mb_substr($this->str, $i, 1, $this->encoding);
  921. }
  922. return static::create($reversed, $this->encoding);
  923. }
  924. /**
  925. * A multibyte str_shuffle() function. It returns a string with its
  926. * characters in random order.
  927. *
  928. * @return Stringy Object with a shuffled $str
  929. */
  930. public function shuffle()
  931. {
  932. $indexes = range(0, $this->length() - 1);
  933. shuffle($indexes);
  934. $shuffledStr = '';
  935. foreach ($indexes as $i) {
  936. $shuffledStr .= mb_substr($this->str, $i, 1, $this->encoding);
  937. }
  938. return static::create($shuffledStr, $this->encoding);
  939. }
  940. /**
  941. * Returns a string with whitespace removed from the start and end of the
  942. * string. Supports the removal of unicode whitespace. Accepts an optional
  943. * string of characters to strip instead of the defaults.
  944. *
  945. * @param string $chars Optional string of characters to strip
  946. * @return Stringy Object with a trimmed $str
  947. */
  948. public function trim($chars = null)
  949. {
  950. $chars = ($chars) ? preg_quote($chars) : '[:space:]';
  951. return $this->regexReplace("^[$chars]+|[$chars]+\$", '');
  952. }
  953. /**
  954. * Returns a string with whitespace removed from the start of the string.
  955. * Supports the removal of unicode whitespace. Accepts an optional
  956. * string of characters to strip instead of the defaults.
  957. *
  958. * @param string $chars Optional string of characters to strip
  959. * @return Stringy Object with a trimmed $str
  960. */
  961. public function trimLeft($chars = null)
  962. {
  963. $chars = ($chars) ? preg_quote($chars) : '[:space:]';
  964. return $this->regexReplace("^[$chars]+", '');
  965. }
  966. /**
  967. * Returns a string with whitespace removed from the end of the string.
  968. * Supports the removal of unicode whitespace. Accepts an optional
  969. * string of characters to strip instead of the defaults.
  970. *
  971. * @param string $chars Optional string of characters to strip
  972. * @return Stringy Object with a trimmed $str
  973. */
  974. public function trimRight($chars = null)
  975. {
  976. $chars = ($chars) ? preg_quote($chars) : '[:space:]';
  977. return $this->regexReplace("[$chars]+\$", '');
  978. }
  979. /**
  980. * Returns the longest common prefix between the string and $otherStr.
  981. *
  982. * @param string $otherStr Second string for comparison
  983. * @return Stringy Object with its $str being the longest common prefix
  984. */
  985. public function longestCommonPrefix($otherStr)
  986. {
  987. $encoding = $this->encoding;
  988. $maxLength = min($this->length(), mb_strlen($otherStr, $encoding));
  989. $longestCommonPrefix = '';
  990. for ($i = 0; $i < $maxLength; $i++) {
  991. $char = mb_substr($this->str, $i, 1, $encoding);
  992. if ($char == mb_substr($otherStr, $i, 1, $encoding)) {
  993. $longestCommonPrefix .= $char;
  994. } else {
  995. break;
  996. }
  997. }
  998. return static::create($longestCommonPrefix, $encoding);
  999. }
  1000. /**
  1001. * Returns the longest common suffix between the string and $otherStr.
  1002. *
  1003. * @param string $otherStr Second string for comparison
  1004. * @return Stringy Object with its $str being the longest common suffix
  1005. */
  1006. public function longestCommonSuffix($otherStr)
  1007. {
  1008. $encoding = $this->encoding;
  1009. $maxLength = min($this->length(), mb_strlen($otherStr, $encoding));
  1010. $longestCommonSuffix = '';
  1011. for ($i = 1; $i <= $maxLength; $i++) {
  1012. $char = mb_substr($this->str, -$i, 1, $encoding);
  1013. if ($char == mb_substr($otherStr, -$i, 1, $encoding)) {
  1014. $longestCommonSuffix = $char . $longestCommonSuffix;
  1015. } else {
  1016. break;
  1017. }
  1018. }
  1019. return static::create($longestCommonSuffix, $encoding);
  1020. }
  1021. /**
  1022. * Returns the longest common substring between the string and $otherStr.
  1023. * In the case of ties, it returns that which occurs first.
  1024. *
  1025. * @param string $otherStr Second string for comparison
  1026. * @return Stringy Object with its $str being the longest common substring
  1027. */
  1028. public function longestCommonSubstring($otherStr)
  1029. {
  1030. // Uses dynamic programming to solve
  1031. // http://en.wikipedia.org/wiki/Longest_common_substring_problem
  1032. $encoding = $this->encoding;
  1033. $stringy = static::create($this->str, $encoding);
  1034. $strLength = $stringy->length();
  1035. $otherLength = mb_strlen($otherStr, $encoding);
  1036. // Return if either string is empty
  1037. if ($strLength == 0 || $otherLength == 0) {
  1038. $stringy->str = '';
  1039. return $stringy;
  1040. }
  1041. $len = 0;
  1042. $end = 0;
  1043. $table = array_fill(0, $strLength + 1,
  1044. array_fill(0, $otherLength + 1, 0));
  1045. for ($i = 1; $i <= $strLength; $i++) {
  1046. for ($j = 1; $j <= $otherLength; $j++) {
  1047. $strChar = mb_substr($stringy->str, $i - 1, 1, $encoding);
  1048. $otherChar = mb_substr($otherStr, $j - 1, 1, $encoding);
  1049. if ($strChar == $otherChar) {
  1050. $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
  1051. if ($table[$i][$j] > $len) {
  1052. $len = $table[$i][$j];
  1053. $end = $i;
  1054. }
  1055. } else {
  1056. $table[$i][$j] = 0;
  1057. }
  1058. }
  1059. }
  1060. $stringy->str = mb_substr($stringy->str, $end - $len, $len, $encoding);
  1061. return $stringy;
  1062. }
  1063. /**
  1064. * Returns the length of the string. An alias for PHP's mb_strlen() function.
  1065. *
  1066. * @return int The number of characters in $str given the encoding
  1067. */
  1068. public function length()
  1069. {
  1070. return mb_strlen($this->str, $this->encoding);
  1071. }
  1072. /**
  1073. * Returns the substring beginning at $start with the specified $length.
  1074. * It differs from the mb_substr() function in that providing a $length of
  1075. * null will return the rest of the string, rather than an empty string.
  1076. *
  1077. * @param int $start Position of the first character to use
  1078. * @param int $length Maximum number of characters used
  1079. * @return Stringy Object with its $str being the substring
  1080. */
  1081. public function substr($start, $length = null)
  1082. {
  1083. $length = $length === null ? $this->length() : $length;
  1084. $str = mb_substr($this->str, $start, $length, $this->encoding);
  1085. return static::create($str, $this->encoding);
  1086. }
  1087. /**
  1088. * Returns the character at $index, with indexes starting at 0.
  1089. *
  1090. * @param int $index Position of the character
  1091. * @return Stringy The character at $index
  1092. */
  1093. public function at($index)
  1094. {
  1095. return $this->substr($index, 1);
  1096. }
  1097. /**
  1098. * Returns the first $n characters of the string.
  1099. *
  1100. * @param int $n Number of characters to retrieve from the start
  1101. * @return Stringy Object with its $str being the first $n chars
  1102. */
  1103. public function first($n)
  1104. {
  1105. $stringy = static::create($this->str, $this->encoding);
  1106. if ($n < 0) {
  1107. $stringy->str = '';
  1108. } else {
  1109. return $stringy->substr(0, $n);
  1110. }
  1111. return $stringy;
  1112. }
  1113. /**
  1114. * Returns the last $n characters of the string.
  1115. *
  1116. * @param int $n Number of characters to retrieve from the end
  1117. * @return Stringy Object with its $str being the last $n chars
  1118. */
  1119. public function last($n)
  1120. {
  1121. $stringy = static::create($this->str, $this->encoding);
  1122. if ($n <= 0) {
  1123. $stringy->str = '';
  1124. } else {
  1125. return $stringy->substr(-$n);
  1126. }
  1127. return $stringy;
  1128. }
  1129. /**
  1130. * Ensures that the string begins with $substring. If it doesn't, it's
  1131. * prepended.
  1132. *
  1133. * @param string $substring The substring to add if not present
  1134. * @return Stringy Object with its $str prefixed by the $substring
  1135. */
  1136. public function ensureLeft($substring)
  1137. {
  1138. $stringy = static::create($this->str, $this->encoding);
  1139. if (!$stringy->startsWith($substring)) {
  1140. $stringy->str = $substring . $stringy->str;
  1141. }
  1142. return $stringy;
  1143. }
  1144. /**
  1145. * Ensures that the string begins with $substring. If it doesn't, it's
  1146. * appended.
  1147. *
  1148. * @param string $substring The substring to add if not present
  1149. * @return Stringy Object with its $str suffixed by the $substring
  1150. */
  1151. public function ensureRight($substring)
  1152. {
  1153. $stringy = static::create($this->str, $this->encoding);
  1154. if (!$stringy->endsWith($substring)) {
  1155. $stringy->str .= $substring;
  1156. }
  1157. return $stringy;
  1158. }
  1159. /**
  1160. * Returns a new string with the prefix $substring removed, if present.
  1161. *
  1162. * @param string $substring The prefix to remove
  1163. * @return Stringy Object having a $str without the prefix $substring
  1164. */
  1165. public function removeLeft($substring)
  1166. {
  1167. $stringy = static::create($this->str, $this->encoding);
  1168. if ($stringy->startsWith($substring)) {
  1169. $substringLength = mb_strlen($substring, $stringy->encoding);
  1170. return $stringy->substr($substringLength);
  1171. }
  1172. return $stringy;
  1173. }
  1174. /**
  1175. * Returns a new string with the suffix $substring removed, if present.
  1176. *
  1177. * @param string $substring The suffix to remove
  1178. * @return Stringy Object having a $str without the suffix $substring
  1179. */
  1180. public function removeRight($substring)
  1181. {
  1182. $stringy = static::create($this->str, $this->encoding);
  1183. if ($stringy->endsWith($substring)) {
  1184. $substringLength = mb_strlen($substring, $stringy->encoding);
  1185. return $stringy->substr(0, $stringy->length() - $substringLength);
  1186. }
  1187. return $stringy;
  1188. }
  1189. /**
  1190. * Returns true if $str matches the supplied pattern, false otherwise.
  1191. *
  1192. * @param string $pattern Regex pattern to match against
  1193. * @return bool Whether or not $str matches the pattern
  1194. */
  1195. private function matchesPattern($pattern)
  1196. {
  1197. $regexEncoding = mb_regex_encoding();
  1198. mb_regex_encoding($this->encoding);
  1199. $match = mb_ereg_match($pattern, $this->str);
  1200. mb_regex_encoding($regexEncoding);
  1201. return $match;
  1202. }
  1203. /**
  1204. * Returns true if the string contains a lower case char, false
  1205. * otherwise.
  1206. *
  1207. * @return bool Whether or not the string contains a lower case character.
  1208. */
  1209. public function hasLowerCase()
  1210. {
  1211. return $this->matchesPattern('.*[[:lower:]]');
  1212. }
  1213. /**
  1214. * Returns true if the string contains an upper case char, false
  1215. * otherwise.
  1216. *
  1217. * @return bool Whether or not the string contains an upper case character.
  1218. */
  1219. public function hasUpperCase()
  1220. {
  1221. return $this->matchesPattern('.*[[:upper:]]');
  1222. }
  1223. /**
  1224. * Returns true if the string contains only alphabetic chars, false
  1225. * otherwise.
  1226. *
  1227. * @return bool Whether or not $str contains only alphabetic chars
  1228. */
  1229. public function isAlpha()
  1230. {
  1231. return $this->matchesPattern('^[[:alpha:]]*$');
  1232. }
  1233. /**
  1234. * Returns true if the string contains only alphabetic and numeric chars,
  1235. * false otherwise.
  1236. *
  1237. * @return bool Whether or not $str contains only alphanumeric chars
  1238. */
  1239. public function isAlphanumeric()
  1240. {
  1241. return $this->matchesPattern('^[[:alnum:]]*$');
  1242. }
  1243. /**
  1244. * Returns true if the string