Stringy.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986
  1. <?php
  2. namespace Stringy;
  3. use ArrayAccess;
  4. use ArrayIterator;
  5. use Countable;
  6. use Exception;
  7. use InvalidArgumentException;
  8. use IteratorAggregate;
  9. use OutOfBoundsException;
  10. class Stringy implements Countable, IteratorAggregate, ArrayAccess
  11. {
  12. /**
  13. * An instance's string.
  14. *
  15. * @var string
  16. */
  17. protected $str;
  18. /**
  19. * The string's encoding, which should be one of the mbstring module's
  20. * supported encodings.
  21. *
  22. * @var string
  23. */
  24. protected $encoding;
  25. /**
  26. * Initializes a Stringy object and assigns both str and encoding properties
  27. * the supplied values. $str is cast to a string prior to assignment, and if
  28. * $encoding is not specified, it defaults to mb_internal_encoding(). Throws
  29. * an InvalidArgumentException if the first argument is an array or object
  30. * without a __toString method.
  31. *
  32. * @param mixed $str Value to modify, after being cast to string
  33. * @param string $encoding The character encoding
  34. * @throws \InvalidArgumentException if an array or object without a
  35. * __toString method is passed as the first argument
  36. */
  37. public function __construct($str = '', $encoding = null)
  38. {
  39. if (is_array($str)) {
  40. throw new InvalidArgumentException(
  41. 'Passed value cannot be an array'
  42. );
  43. } elseif (is_object($str) && !method_exists($str, '__toString')) {
  44. throw new InvalidArgumentException(
  45. 'Passed object must have a __toString method'
  46. );
  47. }
  48. $this->str = (string) $str;
  49. $this->encoding = $encoding ?: \mb_internal_encoding();
  50. }
  51. /**
  52. * Creates a Stringy object and assigns both str and encoding properties
  53. * the supplied values. $str is cast to a string prior to assignment, and if
  54. * $encoding is not specified, it defaults to mb_internal_encoding(). It
  55. * then returns the initialized object. Throws an InvalidArgumentException
  56. * if the first argument is an array or object without a __toString method.
  57. *
  58. * @param mixed $str Value to modify, after being cast to string
  59. * @param string $encoding The character encoding
  60. * @return static A Stringy object
  61. * @throws \InvalidArgumentException if an array or object without a
  62. * __toString method is passed as the first argument
  63. */
  64. public static function create($str = '', $encoding = null)
  65. {
  66. return new static($str, $encoding);
  67. }
  68. /**
  69. * Returns the value in $str.
  70. *
  71. * @return string The current value of the $str property
  72. */
  73. public function __toString()
  74. {
  75. return $this->str;
  76. }
  77. /**
  78. * Returns a new string with $string appended.
  79. *
  80. * @param string $string The string to append
  81. * @return static Object with appended $string
  82. */
  83. public function append($string)
  84. {
  85. return static::create($this->str . $string, $this->encoding);
  86. }
  87. /**
  88. * Returns the character at $index, with indexes starting at 0.
  89. *
  90. * @param int $index Position of the character
  91. * @return static The character at $index
  92. */
  93. public function at($index)
  94. {
  95. return $this->substr($index, 1);
  96. }
  97. /**
  98. * Returns the substring between $start and $end, if found, or an empty
  99. * string. An optional offset may be supplied from which to begin the
  100. * search for the start string.
  101. *
  102. * @param string $start Delimiter marking the start of the substring
  103. * @param string $end Delimiter marking the end of the substring
  104. * @param int $offset Index from which to begin the search
  105. * @return static Object whose $str is a substring between $start and $end
  106. */
  107. public function between($start, $end, $offset = 0)
  108. {
  109. $startIndex = $this->indexOf($start, $offset);
  110. if ($startIndex === false) {
  111. return static::create('', $this->encoding);
  112. }
  113. $substrIndex = $startIndex + \mb_strlen($start, $this->encoding);
  114. $endIndex = $this->indexOf($end, $substrIndex);
  115. if ($endIndex === false) {
  116. return static::create('', $this->encoding);
  117. }
  118. return $this->substr($substrIndex, $endIndex - $substrIndex);
  119. }
  120. /**
  121. * Returns a camelCase version of the string. Trims surrounding spaces,
  122. * capitalizes letters following digits, spaces, dashes and underscores,
  123. * and removes spaces, dashes, as well as underscores.
  124. *
  125. * @return static Object with $str in camelCase
  126. */
  127. public function camelize()
  128. {
  129. $encoding = $this->encoding;
  130. $stringy = $this->trim()->lowerCaseFirst();
  131. $stringy->str = preg_replace('/^[-_]+/', '', $stringy->str);
  132. $stringy->str = preg_replace_callback(
  133. '/[-_\s]+(.)?/u',
  134. function ($match) use ($encoding) {
  135. if (isset($match[1])) {
  136. return \mb_strtoupper($match[1], $encoding);
  137. }
  138. return '';
  139. },
  140. $stringy->str
  141. );
  142. $stringy->str = preg_replace_callback(
  143. '/[\d]+(.)?/u',
  144. function ($match) use ($encoding) {
  145. return \mb_strtoupper($match[0], $encoding);
  146. },
  147. $stringy->str
  148. );
  149. return $stringy;
  150. }
  151. /**
  152. * Returns an array consisting of the characters in the string.
  153. *
  154. * @return array An array of string chars
  155. */
  156. public function chars()
  157. {
  158. $chars = [];
  159. for ($i = 0, $l = $this->length(); $i < $l; $i++) {
  160. $chars[] = $this->at($i)->str;
  161. }
  162. return $chars;
  163. }
  164. /**
  165. * Trims the string and replaces consecutive whitespace characters with a
  166. * single space. This includes tabs and newline characters, as well as
  167. * multibyte whitespace such as the thin space and ideographic space.
  168. *
  169. * @return static Object with a trimmed $str and condensed whitespace
  170. */
  171. public function collapseWhitespace()
  172. {
  173. return $this->regexReplace('[[:space:]]+', ' ')->trim();
  174. }
  175. /**
  176. * Returns true if the string contains $needle, false otherwise. By default
  177. * the comparison is case-sensitive, but can be made insensitive by setting
  178. * $caseSensitive to false.
  179. *
  180. * @param string $needle Substring to look for
  181. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  182. * @return bool Whether or not $str contains $needle
  183. */
  184. public function contains($needle, $caseSensitive = true)
  185. {
  186. $encoding = $this->encoding;
  187. if ($caseSensitive) {
  188. return (\mb_strpos($this->str, $needle, 0, $encoding) !== false);
  189. }
  190. return (\mb_stripos($this->str, $needle, 0, $encoding) !== false);
  191. }
  192. /**
  193. * Returns true if the string contains all $needles, false otherwise. By
  194. * default the comparison is case-sensitive, but can be made insensitive by
  195. * setting $caseSensitive to false.
  196. *
  197. * @param string[] $needles Substrings to look for
  198. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  199. * @return bool Whether or not $str contains $needle
  200. */
  201. public function containsAll($needles, $caseSensitive = true)
  202. {
  203. if (empty($needles)) {
  204. return false;
  205. }
  206. foreach ($needles as $needle) {
  207. if (!$this->contains($needle, $caseSensitive)) {
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. /**
  214. * Returns true if the string contains any $needles, false otherwise. By
  215. * default the comparison is case-sensitive, but can be made insensitive by
  216. * setting $caseSensitive to false.
  217. *
  218. * @param string[] $needles Substrings to look for
  219. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  220. * @return bool Whether or not $str contains $needle
  221. */
  222. public function containsAny($needles, $caseSensitive = true)
  223. {
  224. if (empty($needles)) {
  225. return false;
  226. }
  227. foreach ($needles as $needle) {
  228. if ($this->contains($needle, $caseSensitive)) {
  229. return true;
  230. }
  231. }
  232. return false;
  233. }
  234. /**
  235. * Returns the length of the string, implementing the countable interface.
  236. *
  237. * @return int The number of characters in the string, given the encoding
  238. */
  239. public function count()
  240. {
  241. return $this->length();
  242. }
  243. /**
  244. * Returns the number of occurrences of $substring in the given string.
  245. * By default, the comparison is case-sensitive, but can be made insensitive
  246. * by setting $caseSensitive to false.
  247. *
  248. * @param string $substring The substring to search for
  249. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  250. * @return int The number of $substring occurrences
  251. */
  252. public function countSubstr($substring, $caseSensitive = true)
  253. {
  254. if ($caseSensitive) {
  255. return \mb_substr_count($this->str, $substring, $this->encoding);
  256. }
  257. $str = \mb_strtoupper($this->str, $this->encoding);
  258. $substring = \mb_strtoupper($substring, $this->encoding);
  259. return \mb_substr_count($str, $substring, $this->encoding);
  260. }
  261. /**
  262. * Returns a lowercase and trimmed string separated by dashes. Dashes are
  263. * inserted before uppercase characters (with the exception of the first
  264. * character of the string), and in place of spaces as well as underscores.
  265. *
  266. * @return static Object with a dasherized $str
  267. */
  268. public function dasherize()
  269. {
  270. return $this->delimit('-');
  271. }
  272. /**
  273. * Returns a lowercase and trimmed string separated by the given delimiter.
  274. * Delimiters are inserted before uppercase characters (with the exception
  275. * of the first character of the string), and in place of spaces, dashes,
  276. * and underscores. Alpha delimiters are not converted to lowercase.
  277. *
  278. * @param string $delimiter Sequence used to separate parts of the string
  279. * @return static Object with a delimited $str
  280. */
  281. public function delimit($delimiter)
  282. {
  283. $regexEncoding = $this->regexEncoding();
  284. $this->regexEncoding($this->encoding);
  285. $str = $this->eregReplace('\B([A-Z])', '-\1', $this->trim());
  286. $str = \mb_strtolower($str, $this->encoding);
  287. $str = $this->eregReplace('[-_\s]+', $delimiter, $str);
  288. $this->regexEncoding($regexEncoding);
  289. return static::create($str, $this->encoding);
  290. }
  291. /**
  292. * Returns true if the string ends with $substring, false otherwise. By
  293. * default, the comparison is case-sensitive, but can be made insensitive
  294. * by setting $caseSensitive to false.
  295. *
  296. * @param string $substring The substring to look for
  297. * @param bool $caseSensitive Whether or not to enforce case-sensitivity
  298. * @return bool Whether or not $str ends with $substring
  299. */
  300. public function endsWith($substring, $caseSensitive = true)
  301. {
  302. $substringLength = \mb_strlen($substring, $this->encoding);
  303. $strLength = $this->length();
  304. $endOfStr = \mb_substr($this->str, $strLength - $substringLength,
  305. $substringLength, $this->encoding);
  306. if (!$caseSensitive) {
  307. $substring = \mb_strtolower($substring, $this->encoding);
  308. $endOfStr = \mb_strtolower($endOfStr, $this->encoding);
  309. }
  310. return (string) $substring === $endOfStr;
  311. }
  312. /**
  313. * Returns true if the string ends with any of $substrings, false otherwise.
  314. * By default, the comparison is case-sensitive, but can be made insensitive
  315. * by setting $caseSensitive to false.
  316. *
  317. * @param string[] $substrings Substrings to look for
  318. * @param bool $caseSensitive Whether or not to enforce
  319. * case-sensitivity
  320. * @return bool Whether or not $str ends with $substring
  321. */
  322. public function endsWithAny($substrings, $caseSensitive = true)
  323. {
  324. if (empty($substrings)) {
  325. return false;
  326. }
  327. foreach ($substrings as $substring) {
  328. if ($this->endsWith($substring, $caseSensitive)) {
  329. return true;
  330. }
  331. }
  332. return false;
  333. }
  334. /**
  335. * Ensures that the string begins with $substring. If it doesn't, it's
  336. * prepended.
  337. *
  338. * @param string $substring The substring to add if not present
  339. * @return static Object with its $str prefixed by the $substring
  340. */
  341. public function ensureLeft($substring)
  342. {
  343. $stringy = static::create($this->str, $this->encoding);
  344. if (!$stringy->startsWith($substring)) {
  345. $stringy->str = $substring . $stringy->str;
  346. }
  347. return $stringy;
  348. }
  349. /**
  350. * Ensures that the string ends with $substring. If it doesn't, it's
  351. * appended.
  352. *
  353. * @param string $substring The substring to add if not present
  354. * @return static Object with its $str suffixed by the $substring
  355. */
  356. public function ensureRight($substring)
  357. {
  358. $stringy = static::create($this->str, $this->encoding);
  359. if (!$stringy->endsWith($substring)) {
  360. $stringy->str .= $substring;
  361. }
  362. return $stringy;
  363. }
  364. /**
  365. * Returns the first $n characters of the string.
  366. *
  367. * @param int $n Number of characters to retrieve from the start
  368. * @return static Object with its $str being the first $n chars
  369. */
  370. public function first($n)
  371. {
  372. $stringy = static::create($this->str, $this->encoding);
  373. if ($n < 0) {
  374. $stringy->str = '';
  375. return $stringy;
  376. }
  377. return $stringy->substr(0, $n);
  378. }
  379. /**
  380. * Returns the encoding used by the Stringy object.
  381. *
  382. * @return string The current value of the $encoding property
  383. */
  384. public function getEncoding()
  385. {
  386. return $this->encoding;
  387. }
  388. /**
  389. * Returns a new ArrayIterator, thus implementing the IteratorAggregate
  390. * interface. The ArrayIterator's constructor is passed an array of chars
  391. * in the multibyte string. This enables the use of foreach with instances
  392. * of Stringy\Stringy.
  393. *
  394. * @return \ArrayIterator An iterator for the characters in the string
  395. */
  396. public function getIterator()
  397. {
  398. return new ArrayIterator($this->chars());
  399. }
  400. /**
  401. * Returns true if the string contains a lower case char, false
  402. * otherwise.
  403. *
  404. * @return bool Whether or not the string contains a lower case character.
  405. */
  406. public function hasLowerCase()
  407. {
  408. return $this->matchesPattern('.*[[:lower:]]');
  409. }
  410. /**
  411. * Returns true if the string contains an upper case char, false
  412. * otherwise.
  413. *
  414. * @return bool Whether or not the string contains an upper case character.
  415. */
  416. public function hasUpperCase()
  417. {
  418. return $this->matchesPattern('.*[[:upper:]]');
  419. }
  420. /**
  421. * Convert all HTML entities to their applicable characters. An alias of
  422. * html_entity_decode. For a list of flags, refer to
  423. * http://php.net/manual/en/function.html-entity-decode.php
  424. *
  425. * @param int|null $flags Optional flags
  426. * @return static Object with the resulting $str after being html decoded.
  427. */
  428. public function htmlDecode($flags = ENT_COMPAT)
  429. {
  430. $str = html_entity_decode($this->str, $flags, $this->encoding);
  431. return static::create($str, $this->encoding);
  432. }
  433. /**
  434. * Convert all applicable characters to HTML entities. An alias of
  435. * htmlentities. Refer to http://php.net/manual/en/function.htmlentities.php
  436. * for a list of flags.
  437. *
  438. * @param int|null $flags Optional flags
  439. * @return static Object with the resulting $str after being html encoded.
  440. */
  441. public function htmlEncode($flags = ENT_COMPAT)
  442. {
  443. $str = htmlentities($this->str, $flags, $this->encoding);
  444. return static::create($str, $this->encoding);
  445. }
  446. /**
  447. * Capitalizes the first word of the string, replaces underscores with
  448. * spaces, and strips '_id'.
  449. *
  450. * @return static Object with a humanized $str
  451. */
  452. public function humanize()
  453. {
  454. $str = str_replace(['_id', '_'], ['', ' '], $this->str);
  455. return static::create($str, $this->encoding)->trim()->upperCaseFirst();
  456. }
  457. /**
  458. * Returns the index of the first occurrence of $needle in the string,
  459. * and false if not found. Accepts an optional offset from which to begin
  460. * the search.
  461. *
  462. * @param string $needle Substring to look for
  463. * @param int $offset Offset from which to search
  464. * @return int|bool The occurrence's index if found, otherwise false
  465. */
  466. public function indexOf($needle, $offset = 0)
  467. {
  468. return \mb_strpos($this->str, (string) $needle,
  469. (int) $offset, $this->encoding);
  470. }
  471. /**
  472. * Returns the index of the last occurrence of $needle in the string,
  473. * and false if not found. Accepts an optional offset from which to begin
  474. * the search. Offsets may be negative to count from the last character
  475. * in the string.
  476. *
  477. * @param string $needle Substring to look for
  478. * @param int $offset Offset from which to search
  479. * @return int|bool The last occurrence's index if found, otherwise false
  480. */
  481. public function indexOfLast($needle, $offset = 0)
  482. {
  483. return \mb_strrpos($this->str, (string) $needle,
  484. (int) $offset, $this->encoding);
  485. }
  486. /**
  487. * Inserts $substring into the string at the $index provided.
  488. *
  489. * @param string $substring String to be inserted
  490. * @param int $index The index at which to insert the substring
  491. * @return static Object with the resulting $str after the insertion
  492. */
  493. public function insert($substring, $index)
  494. {
  495. $stringy = static::create($this->str, $this->encoding);
  496. if ($index > $stringy->length()) {
  497. return $stringy;
  498. }
  499. $start = \mb_substr($stringy->str, 0, $index, $stringy->encoding);
  500. $end = \mb_substr($stringy->str, $index, $stringy->length(),
  501. $stringy->encoding);
  502. $stringy->str = $start . $substring . $end;
  503. return $stringy;
  504. }
  505. /**
  506. * Returns true if the string contains only alphabetic chars, false
  507. * otherwise.
  508. *
  509. * @return bool Whether or not $str contains only alphabetic chars
  510. */
  511. public function isAlpha()
  512. {
  513. return $this->matchesPattern('^[[:alpha:]]*$');
  514. }
  515. /**
  516. * Returns true if the string contains only alphabetic and numeric chars,
  517. * false otherwise.
  518. *
  519. * @return bool Whether or not $str contains only alphanumeric chars
  520. */
  521. public function isAlphanumeric()
  522. {
  523. return $this->matchesPattern('^[[:alnum:]]*$');
  524. }
  525. /**
  526. * Returns true if the string contains only whitespace chars, false
  527. * otherwise.
  528. *
  529. * @return bool Whether or not $str contains only whitespace characters
  530. */
  531. public function isBlank()
  532. {
  533. return $this->matchesPattern('^[[:space:]]*$');
  534. }
  535. /**
  536. * Returns true if the string contains only hexadecimal chars, false
  537. * otherwise.
  538. *
  539. * @return bool Whether or not $str contains only hexadecimal chars
  540. */
  541. public function isHexadecimal()
  542. {
  543. return $this->matchesPattern('^[[:xdigit:]]*$');
  544. }
  545. /**
  546. * Returns true if the string is JSON, false otherwise. Unlike json_decode
  547. * in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers,
  548. * in that an empty string is not considered valid JSON.
  549. *
  550. * @return bool Whether or not $str is JSON
  551. */
  552. public function isJson()
  553. {
  554. if (!$this->length()) {
  555. return false;
  556. }
  557. json_decode($this->str);
  558. return (json_last_error() === JSON_ERROR_NONE);
  559. }
  560. /**
  561. * Returns true if the string contains only lower case chars, false
  562. * otherwise.
  563. *
  564. * @return bool Whether or not $str contains only lower case characters
  565. */
  566. public function isLowerCase()
  567. {
  568. return $this->matchesPattern('^[[:lower:]]*$');
  569. }
  570. /**
  571. * Returns true if the string is serialized, false otherwise.
  572. *
  573. * @return bool Whether or not $str is serialized
  574. */
  575. public function isSerialized()
  576. {
  577. return $this->str === 'b:0;' || @unserialize($this->str) !== false;
  578. }
  579. /**
  580. * Returns true if the string is base64 encoded, false otherwise.
  581. *
  582. * @return bool Whether or not $str is base64 encoded
  583. */
  584. public function isBase64()
  585. {
  586. return (base64_encode(base64_decode($this->str, true)) === $this->str);
  587. }
  588. /**
  589. * Returns true if the string contains only lower case chars, false
  590. * otherwise.
  591. *
  592. * @return bool Whether or not $str contains only lower case characters
  593. */
  594. public function isUpperCase()
  595. {
  596. return $this->matchesPattern('^[[:upper:]]*$');
  597. }
  598. /**
  599. * Returns the last $n characters of the string.
  600. *
  601. * @param int $n Number of characters to retrieve from the end
  602. * @return static Object with its $str being the last $n chars
  603. */
  604. public function last($n)
  605. {
  606. $stringy = static::create($this->str, $this->encoding);
  607. if ($n <= 0) {
  608. $stringy->str = '';
  609. return $stringy;
  610. }
  611. return $stringy->substr(-$n);
  612. }
  613. /**
  614. * Returns the length of the string. An alias for PHP's mb_strlen() function.
  615. *
  616. * @return int The number of characters in $str given the encoding
  617. */
  618. public function length()
  619. {
  620. return \mb_strlen($this->str, $this->encoding);
  621. }
  622. /**
  623. * Splits on newlines and carriage returns, returning an array of Stringy
  624. * objects corresponding to the lines in the string.
  625. *
  626. * @return static[] An array of Stringy objects
  627. */
  628. public function lines()
  629. {
  630. $array = $this->split('[\r\n]{1,2}', $this->str);
  631. for ($i = 0; $i < count($array); $i++) {
  632. $array[$i] = static::create($array[$i], $this->encoding);
  633. }
  634. return $array;
  635. }
  636. /**
  637. * Returns the longest common prefix between the string and $otherStr.
  638. *
  639. * @param string $otherStr Second string for comparison
  640. * @return static Object with its $str being the longest common prefix
  641. */
  642. public function longestCommonPrefix($otherStr)
  643. {
  644. $encoding = $this->encoding;
  645. $maxLength = min($this->length(), \mb_strlen($otherStr, $encoding));
  646. $longestCommonPrefix = '';
  647. for ($i = 0; $i < $maxLength; $i++) {
  648. $char = \mb_substr($this->str, $i, 1, $encoding);
  649. if ($char == \mb_substr($otherStr, $i, 1, $encoding)) {
  650. $longestCommonPrefix .= $char;
  651. } else {
  652. break;
  653. }
  654. }
  655. return static::create($longestCommonPrefix, $encoding);
  656. }
  657. /**
  658. * Returns the longest common suffix between the string and $otherStr.
  659. *
  660. * @param string $otherStr Second string for comparison
  661. * @return static Object with its $str being the longest common suffix
  662. */
  663. public function longestCommonSuffix($otherStr)
  664. {
  665. $encoding = $this->encoding;
  666. $maxLength = min($this->length(), \mb_strlen($otherStr, $encoding));
  667. $longestCommonSuffix = '';
  668. for ($i = 1; $i <= $maxLength; $i++) {
  669. $char = \mb_substr($this->str, -$i, 1, $encoding);
  670. if ($char == \mb_substr($otherStr, -$i, 1, $encoding)) {
  671. $longestCommonSuffix = $char . $longestCommonSuffix;
  672. } else {
  673. break;
  674. }
  675. }
  676. return static::create($longestCommonSuffix, $encoding);
  677. }
  678. /**
  679. * Returns the longest common substring between the string and $otherStr.
  680. * In the case of ties, it returns that which occurs first.
  681. *
  682. * @param string $otherStr Second string for comparison
  683. * @return static Object with its $str being the longest common substring
  684. */
  685. public function longestCommonSubstring($otherStr)
  686. {
  687. // Uses dynamic programming to solve
  688. // http://en.wikipedia.org/wiki/Longest_common_substring_problem
  689. $encoding = $this->encoding;
  690. $stringy = static::create($this->str, $encoding);
  691. $strLength = $stringy->length();
  692. $otherLength = \mb_strlen($otherStr, $encoding);
  693. // Return if either string is empty
  694. if ($strLength == 0 || $otherLength == 0) {
  695. $stringy->str = '';
  696. return $stringy;
  697. }
  698. $len = 0;
  699. $end = 0;
  700. $table = array_fill(0, $strLength + 1,
  701. array_fill(0, $otherLength + 1, 0));
  702. for ($i = 1; $i <= $strLength; $i++) {
  703. for ($j = 1; $j <= $otherLength; $j++) {
  704. $strChar = \mb_substr($stringy->str, $i - 1, 1, $encoding);
  705. $otherChar = \mb_substr($otherStr, $j - 1, 1, $encoding);
  706. if ($strChar == $otherChar) {
  707. $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
  708. if ($table[$i][$j] > $len) {
  709. $len = $table[$i][$j];
  710. $end = $i;
  711. }
  712. } else {
  713. $table[$i][$j] = 0;
  714. }
  715. }
  716. }
  717. $stringy->str = \mb_substr($stringy->str, $end - $len, $len, $encoding);
  718. return $stringy;
  719. }
  720. /**
  721. * Converts the first character of the string to lower case.
  722. *
  723. * @return static Object with the first character of $str being lower case
  724. */
  725. public function lowerCaseFirst()
  726. {
  727. $first = \mb_substr($this->str, 0, 1, $this->encoding);
  728. $rest = \mb_substr($this->str, 1, $this->length() - 1,
  729. $this->encoding);
  730. $str = \mb_strtolower($first, $this->encoding) . $rest;
  731. return static::create($str, $this->encoding);
  732. }
  733. /**
  734. * Returns whether or not a character exists at an index. Offsets may be
  735. * negative to count from the last character in the string. Implements
  736. * part of the ArrayAccess interface.
  737. *
  738. * @param mixed $offset The index to check
  739. * @return boolean Whether or not the index exists
  740. */
  741. public function offsetExists($offset)
  742. {
  743. $length = $this->length();
  744. $offset = (int) $offset;
  745. if ($offset >= 0) {
  746. return ($length > $offset);
  747. }
  748. return ($length >= abs($offset));
  749. }
  750. /**
  751. * Returns the character at the given index. Offsets may be negative to
  752. * count from the last character in the string. Implements part of the
  753. * ArrayAccess interface, and throws an OutOfBoundsException if the index
  754. * does not exist.
  755. *
  756. * @param mixed $offset The index from which to retrieve the char
  757. * @return mixed The character at the specified index
  758. * @throws \OutOfBoundsException If the positive or negative offset does
  759. * not exist
  760. */
  761. public function offsetGet($offset)
  762. {
  763. $offset = (int) $offset;
  764. $length = $this->length();
  765. if (($offset >= 0 && $length <= $offset) || $length < abs($offset)) {
  766. throw new OutOfBoundsException('No character exists at the index');
  767. }
  768. return \mb_substr($this->str, $offset, 1, $this->encoding);
  769. }
  770. /**
  771. * Implements part of the ArrayAccess interface, but throws an exception
  772. * when called. This maintains the immutability of Stringy objects.
  773. *
  774. * @param mixed $offset The index of the character
  775. * @param mixed $value Value to set
  776. * @throws \Exception When called
  777. */
  778. public function offsetSet($offset, $value)
  779. {
  780. // Stringy is immutable, cannot directly set char
  781. throw new Exception('Stringy object is immutable, cannot modify char');
  782. }
  783. /**
  784. * Implements part of the ArrayAccess interface, but throws an exception
  785. * when called. This maintains the immutability of Stringy objects.
  786. *
  787. * @param mixed $offset The index of the character
  788. * @throws \Exception When called
  789. */
  790. public function offsetUnset($offset)
  791. {
  792. // Don't allow directly modifying the string
  793. throw new Exception('Stringy object is immutable, cannot unset char');
  794. }
  795. /**
  796. * Pads the string to a given length with $padStr. If length is less than
  797. * or equal to the length of the string, no padding takes places. The
  798. * default string used for padding is a space, and the default type (one of
  799. * 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException
  800. * if $padType isn't one of those 3 values.
  801. *
  802. * @param int $length Desired string length after padding
  803. * @param string $padStr String used to pad, defaults to space
  804. * @param string $padType One of 'left', 'right', 'both'
  805. * @return static Object with a padded $str
  806. * @throws /InvalidArgumentException If $padType isn't one of 'right',
  807. * 'left' or 'both'
  808. */
  809. public function pad($length, $padStr = ' ', $padType = 'right')
  810. {
  811. if (!in_array($padType, ['left', 'right', 'both'])) {
  812. throw new InvalidArgumentException('Pad expects $padType ' .
  813. "to be one of 'left', 'right' or 'both'");
  814. }
  815. switch ($padType) {
  816. case 'left':
  817. return $this->padLeft($length, $padStr);
  818. case 'right':
  819. return $this->padRight($length, $padStr);
  820. default:
  821. return $this->padBoth($length, $padStr);
  822. }
  823. }
  824. /**
  825. * Returns a new string of a given length such that both sides of the
  826. * string are padded. Alias for pad() with a $padType of 'both'.
  827. *
  828. * @param int $length Desired string length after padding
  829. * @param string $padStr String used to pad, defaults to space
  830. * @return static String with padding applied
  831. */
  832. public function padBoth($length, $padStr = ' ')
  833. {
  834. $padding = $length - $this->length();
  835. return $this->applyPadding(floor($padding / 2), ceil($padding / 2),
  836. $padStr);
  837. }
  838. /**
  839. * Returns a new string of a given length such that the beginning of the
  840. * string is padded. Alias for pad() with a $padType of 'left'.
  841. *
  842. * @param int $length Desired string length after padding
  843. * @param string $padStr String used to pad, defaults to space
  844. * @return static String with left padding
  845. */
  846. public function padLeft($length, $padStr = ' ')
  847. {
  848. return $this->applyPadding($length - $this->length(), 0, $padStr);
  849. }
  850. /**
  851. * Returns a new string of a given length such that the end of the string
  852. * is padded. Alias for pad() with a $padType of 'right'.
  853. *
  854. * @param int $length Desired string length after padding
  855. * @param string $padStr String used to pad, defaults to space
  856. * @return static String with right padding
  857. */
  858. public function padRight($length, $padStr = ' ')
  859. {
  860. return $this->applyPadding(0, $length - $this->length(), $padStr);
  861. }
  862. /**
  863. * Returns a new string starting with $string.
  864. *
  865. * @param string $string The string to append
  866. * @return static Object with appended $string
  867. */
  868. public function prepend($string)
  869. {
  870. return static::create($string . $this->str, $this->encoding);
  871. }
  872. /**
  873. * Replaces all occurrences of $pattern in $str by $replacement. An alias
  874. * for mb_ereg_replace(). Note that the 'i' option with multibyte patterns
  875. * in mb_ereg_replace() requires PHP 5.6+ for correct results. This is due
  876. * to a lack of support in the bundled version of Oniguruma in PHP < 5.6,
  877. * and current versions of HHVM (3.8 and below).
  878. *
  879. * @param string $pattern The regular expression pattern
  880. * @param string $replacement The string to replace with
  881. * @param string $options Matching conditions to be used
  882. * @return static Object with the resulting $str after the replacements
  883. */
  884. public function regexReplace($pattern, $replacement, $options = 'msr')
  885. {
  886. $regexEncoding = $this->regexEncoding();
  887. $this->regexEncoding($this->encoding);
  888. $str = $this->eregReplace($pattern, $replacement, $this->str, $options);
  889. $this->regexEncoding($regexEncoding);
  890. return static::create($str, $this->encoding);
  891. }
  892. /**
  893. * Returns a new string with the prefix $substring removed, if present.
  894. *
  895. * @param string $substring The prefix to remove
  896. * @return static Object having a $str without the prefix $substring
  897. */
  898. public function removeLeft($substring)
  899. {
  900. $stringy = static::create($this->str, $this->encoding);
  901. if ($stringy->startsWith($substring)) {
  902. $substringLength = \mb_strlen($substring, $stringy->encoding);
  903. return $stringy->substr($substringLength);
  904. }
  905. return $stringy;
  906. }
  907. /**
  908. * Returns a new string with the suffix $substring removed, if present.
  909. *
  910. * @param string $substring The suffix to remove
  911. * @return static Object having a $str without the suffix $substring
  912. */
  913. public function removeRight($substring)
  914. {
  915. $stringy = static::create($this->str, $this->encoding);
  916. if ($stringy->endsWith($substring)) {
  917. $substringLength = \mb_strlen($substring, $stringy->encoding);
  918. return $stringy->substr(0, $stringy->length() - $substringLength);
  919. }
  920. return $stringy;
  921. }
  922. /**
  923. * Returns a repeated string given a multiplier. An alias for str_repeat.
  924. *
  925. * @param int $multiplier The number of times to repeat the string
  926. * @return static Object with a repeated str
  927. */
  928. public function repeat($multiplier)
  929. {
  930. $repeated = str_repeat($this->str, $multiplier);
  931. return static::create($repeated, $this->encoding);
  932. }
  933. /**
  934. * Replaces all occurrences of $search in $str by $replacement.
  935. *
  936. * @param string $search The needle to search for
  937. * @param string $replacement The string to replace with
  938. * @return static Object with the resulting $str after the replacements
  939. */
  940. public function replace($search, $replacement)
  941. {
  942. return $this->regexReplace(preg_quote($search), $replacement);
  943. }
  944. /**
  945. * Returns a reversed string. A multibyte version of strrev().
  946. *
  947. * @return static Object with a reversed $str
  948. */
  949. public function reverse()
  950. {
  951. $strLength = $this->length();
  952. $reversed = '';
  953. // Loop from last index of string to first
  954. for ($i = $strLength - 1; $i >= 0; $i--) {
  955. $reversed .= \mb_substr($this->str, $i, 1, $this->encoding);
  956. }
  957. return static::create($reversed, $this->encoding);
  958. }
  959. /**
  960. * Truncates the string to a given length, while ensuring that it does not
  961. * split words. If $substring is provided, and truncating occurs, the
  962. * string is further truncated so that the substring may be appended without
  963. * exceeding the desired length.
  964. *
  965. * @param int $length Desired length of the truncated string
  966. * @param string $substring The substring to append if it can fit
  967. * @return static Object with the resulting $str after truncating
  968. */
  969. public function safeTruncate($length, $substring = '')
  970. {
  971. $stringy = static::create($this->str, $this->encoding);
  972. if ($length >= $stringy->length()) {
  973. return $stringy;
  974. }
  975. // Need to further trim the string so we can append the substring
  976. $encoding = $stringy->encoding;
  977. $substringLength = \mb_strlen($substring, $encoding);
  978. $length = $length - $substringLength;
  979. $truncated = \mb_substr($stringy->str, 0, $length, $encoding);
  980. // If the last word was truncated
  981. if (mb_strpos($stringy->str, ' ', $length - 1, $encoding) != $length) {
  982. // Find pos of the last occurrence of a space, get up to that
  983. $lastPos = \mb_strrpos($truncated, ' ', 0, $encoding);
  984. if ($lastPos !== false) {
  985. $truncated = \mb_substr($truncated, 0, $lastPos, $encoding);
  986. }
  987. }
  988. $stringy->str = $truncated . $substring;
  989. return $stringy;
  990. }
  991. /*
  992. * A multibyte str_shuffle() function. It returns a string with its
  993. * characters in random order.
  994. *
  995. * @return static Object with a shuffled $str
  996. */
  997. public function shuffle()
  998. {
  999. $indexes = range(0, $this->length() - 1);
  1000. shuffle($indexes);
  1001. $shuffledStr = '';
  1002. foreach ($indexes as $i) {
  1003. $shuffledStr .= \mb_substr($this->str, $i, 1, $this->encoding);
  1004. }
  1005. return static::create($shuffledStr, $this->encoding);
  1006. }
  1007. /**
  1008. * Converts the string into an URL slug. This includes replacing non-ASCII
  1009. * characters with their closest ASCII equivalents, removing remaining
  1010. * non-ASCII and non-alphanumeric characters, and replacing whitespace with
  1011. * $replacement. The replacement defaults to a single dash, and the string
  1012. * is also converted to lowercase. The language of the source string can
  1013. * also be supplied for language-specific transliteration.
  1014. *
  1015. * @param string $replacement The string used to replace whitespace
  1016. * @param string $language Language of the source string
  1017. * @return static Object whose $str has been converted to an URL slug
  1018. */
  1019. public function slugify($replacement = '-', $language = 'en')
  1020. {
  1021. $stringy = $this->toAscii($language);
  1022. $stringy->str = str_replace('@', $replacement, $stringy);
  1023. $quotedReplacement = preg_quote($replacement);
  1024. $pattern = "/[^a-zA-Z\d\s-_$quotedReplacement]/u";
  1025. $stringy->str = preg_replace($pattern, '', $stringy);
  1026. return $stringy->toLowerCase()->delimit($replacement)
  1027. ->removeLeft($replacement)->removeRight($replacement);
  1028. }
  1029. /**
  1030. * Returns true if the string begins with $substring, false otherwise. By
  1031. * default, the comparison is case-sensitive, but can be made insensitive
  1032. * by setting $caseSensitive to false.
  1033. *
  1034. * @param string $substring The substring to look for
  1035. * @param bool $caseSensitive Whether or not to enforce
  1036. * case-sensitivity
  1037. * @return bool Whether or not $str starts with $substring
  1038. */
  1039. public function startsWith($substring, $caseSensitive = true)
  1040. {
  1041. $substringLength = \mb_strlen($substring, $this->encoding);
  1042. $startOfStr = \mb_substr($this->str, 0, $substringLength,
  1043. $this->encoding);
  1044. if (!$caseSensitive) {
  1045. $substring = \mb_strtolower($substring, $this->encoding);
  1046. $startOfStr = \mb_strtolower($startOfStr, $this->encoding);
  1047. }
  1048. return (string) $substring === $startOfStr;
  1049. }
  1050. /**
  1051. * Returns true if the string begins with any of $substrings, false
  1052. * otherwise. By default the comparison is case-sensitive, but can be made
  1053. * insensitive by setting $caseSensitive to false.
  1054. *
  1055. * @param string[] $substrings Substrings to look for
  1056. * @param bool $caseSensitive Whether or not to enforce
  1057. * case-sensitivity
  1058. * @return bool Whether or not $str starts with $substring
  1059. */
  1060. public function startsWithAny($substrings, $caseSensitive = true)
  1061. {
  1062. if (empty($substrings)) {
  1063. return false;
  1064. }
  1065. foreach ($substrings as $substring) {
  1066. if ($this->startsWith($substring, $caseSensitive)) {
  1067. return true;
  1068. }
  1069. }
  1070. return false;
  1071. }
  1072. /**
  1073. * Returns the substring beginning at $start, and up to, but not including
  1074. * the index specified by $end. If $end is omitted, the function extracts
  1075. * the remaining string. If $end is negative, it is computed from the end
  1076. * of the string.
  1077. *
  1078. * @param int $start Initial index from which to begin extraction
  1079. * @param int $end Optional index at which to end extraction
  1080. * @return static Object with its $str being the extracted substring
  1081. */
  1082. public function slice($start, $end = null)
  1083. {
  1084. if ($end === null) {
  1085. $length = $this->length();
  1086. } elseif ($end >= 0 && $end <= $start) {
  1087. return static::create('', $this->encoding);
  1088. } elseif ($end < 0) {
  1089. $length = $this->length() + $end - $start;
  1090. } else {
  1091. $length = $end - $start;
  1092. }
  1093. return $this->substr($start, $length);
  1094. }
  1095. /**
  1096. * Splits the string with the provided regular expression, returning an
  1097. * array of Stringy objects. An optional integer $limit will truncate the
  1098. * results.
  1099. *
  1100. * @param string $pattern The regex with which to split the string
  1101. * @param int $limit Optional maximum number of results to return
  1102. * @return static[] An array of Stringy objects
  1103. */
  1104. public function split($pattern, $limit = null)
  1105. {
  1106. if ($limit === 0) {
  1107. return [];
  1108. }
  1109. // mb_split errors when supplied an empty pattern in < PHP 5.4.13
  1110. // and HHVM < 3.8
  1111. if ($pattern === '') {
  1112. return [static::create($this->str, $this->encoding)];
  1113. }
  1114. $regexEncoding = $this->regexEncoding();
  1115. $this->regexEncoding($this->encoding);
  1116. // mb_split returns the remaining unsplit string in the last index when
  1117. // supplying a limit
  1118. $limit = ($limit > 0) ? $limit += 1 : -1;
  1119. static $functionExists;
  1120. if ($functionExists === null) {
  1121. $functionExists = function_exists('\mb_split');
  1122. }
  1123. if ($functionExists) {
  1124. $array = \mb_split($pattern, $this->str, $limit);
  1125. } else if ($this->supportsEncoding()) {
  1126. $array = \preg_split("/$pattern/", $this->str, $limit);
  1127. }
  1128. $this->regexEncoding($regexEncoding);
  1129. if ($limit > 0 && count($array) === $limit) {
  1130. array_pop($array);
  1131. }
  1132. for ($i = 0; $i < count($array); $i++) {
  1133. $array[$i] = static::create($array[$i], $this->encoding);
  1134. }
  1135. return $array;
  1136. }
  1137. /**
  1138. * Strip all whitespace characters. This includes tabs and newline
  1139. * characters, as well as multibyte whitespace such as the thin space
  1140. * and ideographic space.
  1141. *
  1142. * @return static Object with whitespace stripped
  1143. */
  1144. public function stripWhitespace()
  1145. {
  1146. return $this->regexReplace('[[:space:]]+', '');
  1147. }
  1148. /**
  1149. * Returns the substring beginning at $start with the specified $length.
  1150. * It differs from the mb_substr() function in that providing a $length of
  1151. * null will return the rest of the string, rather than an empty string.
  1152. *
  1153. * @param int $start Position of the first character to use
  1154. * @param int $length Maximum number of characters used
  1155. * @return static Object with its $str being the substring
  1156. */
  1157. public function substr($start, $length = null)
  1158. {
  1159. $length = $length === null ? $this->length() : $length;
  1160. $str = \mb_substr($this->str, $start, $length, $this->encoding);
  1161. return static::create($str, $this->encoding);
  1162. }
  1163. /**
  1164. * Surrounds $str with the given substring.
  1165. *
  1166. * @param string $substring The substring to add to both sides
  1167. * @return static Object whose $str had the substring both prepended and
  1168. * appended
  1169. */
  1170. public function surround($substring)
  1171. {
  1172. $str = implode('', [$substring, $this->str, $substring]);
  1173. return static::create($str, $this->encoding);
  1174. }
  1175. /**
  1176. * Returns a case swapped version of the string.
  1177. *
  1178. * @return static Object whose $str has each character's case swapped
  1179. */
  1180. public function swapCase()
  1181. {
  1182. $stringy = static::create($this->str, $this->encoding);
  1183. $encoding = $stringy->encoding;
  1184. $stringy->str = preg_replace_callback(
  1185. '/[\S]/u',
  1186. function ($match) use ($encoding) {
  1187. if ($match[0] == \mb_strtoupper($match[0], $encoding)) {
  1188. return \mb_strtolower($match[0], $encoding);
  1189. }
  1190. return \mb_strtoupper($match[0], $encoding);
  1191. },
  1192. $stringy->str
  1193. );
  1194. return $stringy;
  1195. }
  1196. /**
  1197. * Returns a string with smart quotes, ellipsis characters, and dashes from
  1198. * Windows-1252 (commonly used in Word documents) replaced by their ASCII
  1199. * equivalents.
  1200. *
  1201. * @return static Object whose $str has those characters removed
  1202. */
  1203. public function tidy()
  1204. {
  1205. $str = preg_replace([
  1206. '/\x{2026}/u',
  1207. '/[\x{201C}\x{201D}]/u',
  1208. '/[\x{2018}\x{2019}]/u',
  1209. '/[\x{2013}\x{2014}]/u',
  1210. ], [
  1211. '...',
  1212. '"',
  1213. "'",
  1214. '-',
  1215. ], $this->str);
  1216. return static::create($str, $this->encoding);
  1217. }
  1218. /**
  1219. * Returns a trimmed string with the first letter of each word capitalized.
  1220. * Also accepts an array, $ignore, allowing you to list words not to be
  1221. * capitalized.
  1222. *
  1223. * @param array $ignore An array of words not to capitalize
  1224. * @return static Object with a titleized $str
  1225. */
  1226. public function titleize($ignore = null)
  1227. {
  1228. $stringy = static::create($this->trim(), $this->encoding);
  1229. $encoding = $this->encoding;
  1230. $stringy->str = preg_replace_callback(
  1231. '/([\S]+)/u',
  1232. function ($match) use ($encoding, $ignore) {
  1233. if ($ignore && in_array($match[0], $ignore)) {
  1234. return $match[0];
  1235. }
  1236. $stringy = new Stringy($match[0], $encoding);
  1237. return (string) $stringy->toLowerCase()->upperCaseFirst();
  1238. },
  1239. $stringy->str
  1240. );
  1241. return $stringy;
  1242. }
  1243. /**
  1244. * Returns an ASCII version of the string. A set of non-ASCII characters are
  1245. * replaced with their closest ASCII counterparts, and the rest are removed
  1246. * by default. The language or locale of the source string can be supplied
  1247. * for language-specific transliteration in any of the following formats:
  1248. * en, en_GB, or en-GB. For example, passing "de" results in "äöü" mapping
  1249. * to "aeoeue" rather than "aou" as in other languages.
  1250. *
  1251. * @param string $language Language of the source string
  1252. * @param bool $removeUnsupported Whether or not to remove the
  1253. * unsupported characters
  1254. * @return static Object whose $str contains only ASCII characters
  1255. */
  1256. public function toAscii($language = 'en', $removeUnsupported = true)
  1257. {
  1258. $str = $this->str;
  1259. $langSpecific = $this->langSpecificCharsArray($language);
  1260. if (!empty($langSpecific)) {
  1261. $str = str_replace($langSpecific[0], $langSpecific[1], $str);
  1262. }
  1263. foreach ($this->charsArray() as $key => $value) {
  1264. $str = str_replace($value, $key, $str);
  1265. }
  1266. if ($removeUnsupported) {
  1267. $str = preg_replace('/[^\x20-\x7E]/u', '', $str);
  1268. }
  1269. return static::create($str, $this->encoding);
  1270. }
  1271. /**
  1272. * Returns a boolean representation of the given logical string value.
  1273. * For example, 'true', '1', 'on' and 'yes' will return true. 'false', '0',
  1274. * 'off', and 'no' will return false. In all instances, case is ignored.
  1275. * For other numeric strings, their sign will determine the return value.
  1276. * In addition, blank strings consisting of only whitespace will return
  1277. * false. For all other strings, the return value is a result of a
  1278. * boolean cast.
  1279. *
  1280. * @return bool A boolean value for the string
  1281. */
  1282. public function toBoolean()
  1283. {
  1284. $key = $this->toLowerCase()->str;
  1285. $map = [
  1286. 'true' => true,
  1287. '1' => true,
  1288. 'on' => true,
  1289. 'yes' => true,
  1290. 'false' => false,
  1291. '0' => false,
  1292. 'off' => false,
  1293. 'no' => false
  1294. ];
  1295. if (array_key_exists($key, $map)) {
  1296. return $map[$key];
  1297. } elseif (is_numeric($this->str)) {
  1298. return (intval($this->str) > 0);
  1299. }
  1300. return (bool) $this->regexReplace('[[:space:]]', '')->str;
  1301. }
  1302. /**
  1303. * Converts all characters in the string to lowercase. An alias for PHP's
  1304. * mb_strtolower().
  1305. *
  1306. * @return static Object with all characters of $str being lowercase
  1307. */
  1308. public function toLowerCase()
  1309. {
  1310. $str = \mb_strtolower($this->str, $this->encoding);
  1311. return static::create($str, $this->encoding);
  1312. }
  1313. /**
  1314. * Converts each tab in the string to some number of spaces, as defined by
  1315. * $tabLength. By default, each tab is converted to 4 consecutive spaces.
  1316. *
  1317. * @param int $tabLength Number of spaces to replace each tab with
  1318. * @return static Object whose $str has had tabs switched to spaces
  1319. */
  1320. public function toSpaces($tabLength = 4)
  1321. {
  1322. $spaces = str_repeat(' ', $tabLength);
  1323. $str = str_replace("\t", $spaces, $this->str);
  1324. return static::create($str, $this->encoding);
  1325. }
  1326. /**
  1327. * Converts each occurrence of some consecutive number of spaces, as
  1328. * defined by $tabLength, to a tab. By default, each 4 consecutive spaces
  1329. * are converted to a tab.
  1330. *
  1331. * @param int $tabLength Number of spaces to replace with a tab
  1332. * @return static Object whose $str has had spaces switched to tabs
  1333. */
  1334. public function toTabs($tabLength = 4)
  1335. {
  1336. $spaces = str_repeat(' ', $tabLength);
  1337. $str = str_replace($spaces, "\t", $this->str);
  1338. return static::create($str, $this->encoding);
  1339. }
  1340. /**
  1341. * Converts the first character of each word in the string to uppercase.
  1342. *
  1343. * @return static Object with all characters of $str being title-cased
  1344. */
  1345. public function toTitleCase()
  1346. {
  1347. $str = \mb_convert_case($this->str, \MB_CASE_TITLE, $this->encoding);
  1348. return static::create($str, $this->encoding);
  1349. }
  1350. /**
  1351. * Converts all characters in the string to uppercase. An alias for PHP's
  1352. * mb_strtoupper().
  1353. *
  1354. * @return static Object with all characters of $str being uppercase
  1355. */
  1356. public function toUpperCase()
  1357. {
  1358. $str = \mb_strtoupper($this->str, $this->encoding);
  1359. return static::create($str, $this->encoding);
  1360. }
  1361. /**
  1362. * Returns a string with whitespace removed from the start and end of the
  1363. * string. Supports the removal of unicode whitespace. Accepts an optional
  1364. * string of characters to strip instead of the defaults.
  1365. *
  1366. * @param string $chars Optional string of characters to strip
  1367. * @return static Object with a trimmed $str
  1368. */
  1369. public function trim($chars = null)
  1370. {
  1371. $chars = ($chars) ? preg_quote($chars) : '[:space:]';
  1372. return $this->regexReplace("^[$chars]+|[$chars]+\$", '');
  1373. }
  1374. /**
  1375. * Returns a string with whitespace removed from the start of the string.
  1376. * Supports the removal of unicode whitespace. Accepts an optional
  1377. * string of characters to strip instead of the defaults.
  1378. *
  1379. * @param string $chars Optional string of characters to strip
  1380. * @return static Object with a trimmed $str
  1381. */
  1382. public function trimLeft($chars = null)
  1383. {
  1384. $chars = ($chars) ? preg_quote($chars) : '[:space:]';
  1385. return $this->regexReplace("^[$chars]+", '');
  1386. }
  1387. /**
  1388. * Returns a string with whitespace removed from the end of the string.
  1389. * Supports the removal of unicode whitespace. Accepts an optional
  1390. * string of characters to strip instead of the defaults.
  1391. *
  1392. * @param string $chars Optional string of characters to strip
  1393. * @return static Object with a trimmed $str
  1394. */
  1395. public function trimRight($chars = null)
  1396. {
  1397. $chars = ($chars) ? preg_quote($chars) : '[:space:]';
  1398. return $this->regexReplace("[$chars]+\$", '');
  1399. }
  1400. /**
  1401. * Truncates the string to a given length. If $substring is provided, and
  1402. * truncating occurs, the string is further truncated so that the substring
  1403. * may be appended without exceeding the desired length.
  1404. *
  1405. * @param int $length Desired length of the truncated string
  1406. * @param string $substring The substring to append if it can fit
  1407. * @return static Object with the resulting $str after truncating
  1408. */
  1409. public function truncate($length, $substring = '')
  1410. {
  1411. $stringy = static::create($this->str, $this->encoding);
  1412. if ($length >= $stringy->length()) {
  1413. return $stringy;
  1414. }
  1415. // Need to further trim the string so we can append the substring
  1416. $substringLength = \mb_strlen($substring, $stringy->encoding);
  1417. $length = $length - $substringLength;
  1418. $truncated = \mb_substr($stringy->str, 0, $length, $stringy->encoding);
  1419. $stringy->str = $truncated . $substring;
  1420. return $stringy;
  1421. }
  1422. /**
  1423. * Returns a lowercase and trimmed string separated by underscores.
  1424. * Underscores are inserted before uppercase characters (with the exception
  1425. * of the first character of the string), and in place of spaces as well as
  1426. * dashes.
  1427. *
  1428. * @return static Object with an underscored $str
  1429. */
  1430. public function underscored()
  1431. {
  1432. return $this->delimit('_');
  1433. }
  1434. /**
  1435. * Returns an UpperCamelCase version of the supplied string. It trims
  1436. * surrounding spaces, capitalizes letters following digits, spaces, dashes
  1437. * and underscores, and removes spaces, dashes, underscores.
  1438. *
  1439. * @return static Object with $str in UpperCamelCase
  1440. */
  1441. public function upperCamelize()
  1442. {
  1443. return $this->camelize()->upperCaseFirst();
  1444. }
  1445. /**
  1446. * Converts the first character of the supplied string to upper case.
  1447. *
  1448. * @return static Object with the first character of $str being upper case
  1449. */
  1450. public function upperCaseFirst()
  1451. {
  1452. $first = \mb_substr($this->str, 0, 1, $this->encoding);
  1453. $rest = \mb_substr($this->str, 1, $this->length() - 1,
  1454. $this->encoding);
  1455. $str = \mb_strtoupper($first, $this->encoding) . $rest;
  1456. return static::create($str, $this->encoding);
  1457. }
  1458. /**
  1459. * Returns the replacements for the toAscii() method.
  1460. *
  1461. * @return array An array of replacements.
  1462. */
  1463. protected function charsArray()
  1464. {
  1465. static $charsArray;
  1466. if (isset($charsArray)) return $charsArray;
  1467. return $charsArray = [
  1468. '0' => ['°', '₀', '۰', '0'],
  1469. '1' => ['¹', '₁', '۱', '1'],
  1470. '2' => ['²', '₂', '۲', '2'],
  1471. '3' => ['³', '₃', '۳', '3'],
  1472. '4' => ['⁴', '₄', '۴', '٤', '4'],
  1473. '5' => ['⁵', '₅', '۵', '٥', '5'],
  1474. '6' => ['⁶', '₆', '۶', '٦', '6'],
  1475. '7' => ['⁷', '₇', '۷', '7'],
  1476. '8' => ['⁸', '₈', '۸', '8'],
  1477. '9' => ['⁹', '₉', '۹', '9'],
  1478. 'a' => ['à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ',
  1479. 'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ā', 'ą', 'å',
  1480. 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ', 'ἇ',
  1481. 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ', 'ά',
  1482. 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ', 'အ',
  1483. 'ာ', 'ါ', 'ǻ', 'ǎ', 'ª', 'ა', 'अ', 'ا', 'a', 'ä'],
  1484. 'b' => ['б', 'β', 'ب', 'ဗ', 'ბ', 'b'],
  1485. 'c' => ['ç', 'ć', 'č', 'ĉ', 'ċ', 'c'],
  1486. 'd' => ['ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ',
  1487. 'д', 'δ', 'د', 'ض', 'ဍ', 'ဒ', 'დ', 'd'],
  1488. 'e' => ['é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ',
  1489. 'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ',
  1490. 'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э',
  1491. 'є', 'ə', 'ဧ', 'ေ', 'ဲ', 'ე', 'ए', 'إ', 'ئ', 'e'],
  1492. 'f' => ['ф', 'φ', 'ف', 'ƒ', 'ფ', 'f'],
  1493. 'g' => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ဂ', 'გ', 'گ',
  1494. 'g'],
  1495. 'h' => ['ĥ', 'ħ', 'η', 'ή', 'ح', 'ه', 'ဟ', 'ှ', 'ჰ', 'h'],
  1496. 'i' => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į',
  1497. 'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ',
  1498. 'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ',
  1499. 'ῗ', 'і', 'ї', 'и', 'ဣ', 'ိ', 'ီ', 'ည်', 'ǐ', 'ი',
  1500. 'इ', 'ی', 'i'],
  1501. 'j' => ['ĵ', 'ј', 'Ј', 'ჯ', 'ج', 'j'],
  1502. 'k' => ['ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك', 'က', 'კ', 'ქ',
  1503. 'ک', 'k'],
  1504. 'l' => ['ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل', 'လ', 'ლ',
  1505. 'l'],
  1506. 'm' => ['м', 'μ', 'م', 'မ', 'მ', 'm'],
  1507. 'n' => ['ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن', 'န',
  1508. 'ნ', 'n'],
  1509. 'o' => ['ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ',
  1510. 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő',
  1511. 'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό',
  1512. 'о', 'و', 'θ', 'ို', 'ǒ', 'ǿ', 'º', 'ო', 'ओ', 'o',
  1513. 'ö'],
  1514. 'p' => ['п', 'π', 'ပ', 'პ', 'پ', 'p'],
  1515. 'q' => ['ყ', 'q'],
  1516. 'r' => ['ŕ', 'ř', 'ŗ', 'р', 'ρ', 'ر', 'რ', 'r'],
  1517. 's' => ['ś', 'š', 'ş', 'с', 'σ', 'ș', 'ς', 'س', 'ص', 'စ',
  1518. 'ſ', 'ს', 's'],
  1519. 't' => ['ť', 'ţ', 'т', 'τ', 'ț', 'ت', 'ط', 'ဋ', 'တ', 'ŧ',
  1520. 'თ', 'ტ', 't'],
  1521. 'u' => ['ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ',
  1522. 'ự', 'û', 'ū', 'ů', 'ű', 'ŭ', 'ų', 'µ', 'у', 'ဉ',
  1523. 'ု', 'ူ', 'ǔ', 'ǖ', 'ǘ', 'ǚ', 'ǜ', 'უ', 'उ', 'u',
  1524. 'ў', 'ü'],
  1525. 'v' => ['в', 'ვ', 'ϐ', 'v'],
  1526. 'w' => ['ŵ', 'ω', 'ώ', 'ဝ', 'ွ', 'w'],
  1527. 'x' => ['χ', 'ξ', 'x'],
  1528. 'y' => ['ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'ÿ', 'ŷ', 'й', 'ы', 'υ',
  1529. 'ϋ', 'ύ', 'ΰ', 'ي', 'ယ', 'y'],
  1530. 'z' => ['ź', 'ž', 'ż', 'з', 'ζ', 'ز', 'ဇ', 'ზ', 'z'],
  1531. 'aa' => ['ع', 'आ', 'آ'],
  1532. 'ae' => ['æ', 'ǽ'],
  1533. 'ai' => ['ऐ'],
  1534. 'ch' => ['ч', 'ჩ', 'ჭ', 'چ'],
  1535. 'dj' => ['ђ', 'đ'],
  1536. 'dz' => ['џ', 'ძ'],
  1537. 'ei' => ['ऍ'],
  1538. 'gh' => ['غ', 'ღ'],
  1539. 'ii' => ['ई'],
  1540. 'ij' => ['ij'],
  1541. 'kh' => ['х', 'خ', 'ხ'],
  1542. 'lj' => ['љ'],
  1543. 'nj' => ['њ'],
  1544. 'oe' => ['œ', 'ؤ'],
  1545. 'oi' => ['ऑ'],
  1546. 'oii' => ['ऒ'],
  1547. 'ps' => ['ψ'],
  1548. 'sh' => ['ш', 'შ', 'ش'],
  1549. 'shch' => ['щ'],
  1550. 'ss' => ['ß'],
  1551. 'sx' => ['ŝ'],
  1552. 'th' => ['þ', 'ϑ', 'ث', 'ذ', 'ظ'],
  1553. 'ts' => ['ц', 'ც', 'წ'],
  1554. 'uu' => ['ऊ'],
  1555. 'ya' => ['я'],
  1556. 'yu' => ['ю'],
  1557. 'zh' => ['ж', 'ჟ', 'ژ'],
  1558. '(c)' => ['©'],
  1559. 'A' => ['Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ',
  1560. 'Ặ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Å', 'Ā', 'Ą',
  1561. 'Α', 'Ά', 'Ἀ', 'Ἁ', 'Ἂ', 'Ἃ', 'Ἄ', 'Ἅ', 'Ἆ', 'Ἇ',
  1562. 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ', 'Ᾱ',
  1563. 'Ὰ', 'Ά', 'ᾼ', 'А', 'Ǻ', 'Ǎ', 'A', 'Ä'],
  1564. 'B' => ['Б', 'Β', 'ब', 'B'],
  1565. 'C' => ['Ç','Ć', 'Č', 'Ĉ', 'Ċ', 'C'],
  1566. 'D' => ['Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ',
  1567. 'D'],
  1568. 'E' => ['É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ',
  1569. 'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ',
  1570. 'Ἑ', 'Ἒ', 'Ἓ', 'Ἔ', 'Ἕ', 'Έ', 'Ὲ', 'Е', 'Ё', 'Э',
  1571. 'Є', 'Ə', 'E'],
  1572. 'F' => ['Ф', 'Φ', 'F'],
  1573. 'G' => ['Ğ', 'Ġ', 'Ģ', 'Г', 'Ґ', 'Γ', 'G'],
  1574. 'H' => ['Η', 'Ή', 'Ħ', 'H'],
  1575. 'I' => ['Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'Î', 'Ï', 'Ī', 'Ĭ', 'Į',
  1576. 'İ', 'Ι', 'Ί', 'Ϊ', 'Ἰ', 'Ἱ', 'Ἳ', 'Ἴ', 'Ἵ', 'Ἶ',
  1577. 'Ἷ', 'Ῐ', 'Ῑ', 'Ὶ', 'Ί', 'И', 'І', 'Ї', 'Ǐ', 'ϒ',
  1578. 'I'],
  1579. 'J' => ['J'],
  1580. 'K' => ['К', 'Κ', 'K'],
  1581. 'L' => ['Ĺ', 'Ł', 'Л', 'Λ', 'Ļ', 'Ľ', 'Ŀ', 'ल', 'L'],
  1582. 'M' => ['М', 'Μ', 'M'],
  1583. 'N' => ['Ń', 'Ñ', 'Ň', 'Ņ', 'Ŋ', 'Н', 'Ν', 'N'],
  1584. 'O' => ['Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ',
  1585. 'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'Ø', 'Ō', 'Ő',
  1586. 'Ŏ', 'Ο', 'Ό', 'Ὀ', 'Ὁ', 'Ὂ', 'Ὃ', 'Ὄ', 'Ὅ', 'Ὸ',
  1587. 'Ό', 'О', 'Θ', 'Ө', 'Ǒ', 'Ǿ', 'O', 'Ö'],
  1588. 'P' => ['П', 'Π', 'P'],
  1589. 'Q' => ['Q'],
  1590. 'R' => ['Ř', 'Ŕ', 'Р', 'Ρ', 'Ŗ', 'R'],
  1591. 'S' => ['Ş', 'Ŝ', 'Ș', 'Š', 'Ś', 'С', 'Σ', 'S'],
  1592. 'T' => ['Ť', 'Ţ', 'Ŧ', 'Ț', 'Т', 'Τ', 'T'],
  1593. 'U' => ['Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ',
  1594. 'Ự', 'Û', 'Ū', 'Ů', 'Ű', 'Ŭ', 'Ų', 'У', 'Ǔ', 'Ǖ',
  1595. 'Ǘ', 'Ǚ', 'Ǜ', 'U', 'Ў', 'Ü'],
  1596. 'V' => ['В', 'V'],
  1597. 'W' => ['Ω', 'Ώ', 'Ŵ', 'W'],
  1598. 'X' => ['Χ', 'Ξ', 'X'],
  1599. 'Y' => ['Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Ÿ', 'Ῠ', 'Ῡ', 'Ὺ', 'Ύ',
  1600. 'Ы', 'Й', 'Υ', 'Ϋ', 'Ŷ', 'Y'],
  1601. 'Z' => ['Ź', 'Ž', 'Ż', 'З', 'Ζ', 'Z'],
  1602. 'AE' => ['Æ', 'Ǽ'],
  1603. 'Ch' => ['Ч'],
  1604. 'Dj' => ['Ђ'],
  1605. 'Dz' => ['Џ'],
  1606. 'Gx' => ['Ĝ'],
  1607. 'Hx' => ['Ĥ'],
  1608. 'Ij' => ['IJ'],
  1609. 'Jx' => ['Ĵ'],
  1610. 'Kh' => ['Х'],
  1611. 'Lj' => ['Љ'],
  1612. 'Nj' => ['Њ'],
  1613. 'Oe' => ['Œ'],
  1614. 'Ps' => ['Ψ'],
  1615. 'Sh' => ['Ш'],
  1616. 'Shch' => ['Щ'],
  1617. 'Ss' => ['ẞ'],
  1618. 'Th' => ['Þ'],
  1619. 'Ts' => ['Ц'],
  1620. 'Ya' => ['Я'],
  1621. 'Yu' => ['Ю'],
  1622. 'Zh' => ['Ж'],
  1623. ' ' => ["\xC2\xA0", "\xE2\x80\x80", "\xE2\x80\x81",
  1624. "\xE2\x80\x82", "\xE2\x80\x83", "\xE2\x80\x84",
  1625. "\xE2\x80\x85", "\xE2\x80\x86", "\xE2\x80\x87",
  1626. "\xE2\x80\x88", "\xE2\x80\x89", "\xE2\x80\x8A",
  1627. "\xE2\x80\xAF", "\xE2\x81\x9F", "\xE3\x80\x80",
  1628. "\xEF\xBE\xA0"],
  1629. ];
  1630. }
  1631. /**
  1632. * Returns language-specific replacements for the toAscii() method.
  1633. * For example, German will map 'ä' to 'ae', while other languages
  1634. * will simply return 'a'.
  1635. *
  1636. * @param string $language Language of the source string
  1637. * @return array An array of replacements.
  1638. */
  1639. protected static function langSpecificCharsArray($language = 'en')
  1640. {
  1641. $split = preg_split('/[-_]/', $language);
  1642. $language = strtolower($split[0]);
  1643. static $charsArray = [];
  1644. if (isset($charsArray[$language])) {
  1645. return $charsArray[$language];
  1646. }
  1647. $languageSpecific = [
  1648. 'de' => [
  1649. ['ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü' ],
  1650. ['ae', 'oe', 'ue', 'AE', 'OE', 'UE'],
  1651. ],
  1652. 'bg' => [
  1653. ['х', 'Х', 'щ', 'Щ', 'ъ', 'Ъ', 'ь', 'Ь'],
  1654. ['h', 'H', 'sht', 'SHT', 'a', 'А', 'y', 'Y']
  1655. ]
  1656. ];
  1657. if (isset($languageSpecific[$language])) {
  1658. $charsArray[$language] = $languageSpecific[$language];
  1659. } else {
  1660. $charsArray[$language] = [];
  1661. }
  1662. return $charsArray[$language];
  1663. }
  1664. /**
  1665. * Adds the specified amount of left and right padding to the given string.
  1666. * The default character used is a space.
  1667. *
  1668. * @param int $left Length of left padding
  1669. * @param int $right Length of right padding
  1670. * @param string $padStr String used to pad
  1671. * @return static String with padding applied
  1672. */
  1673. protected function applyPadding($left = 0, $right = 0, $padStr = ' ')
  1674. {
  1675. $stringy = static::create($this->str, $this->encoding);
  1676. $length = \mb_strlen($padStr, $stringy->encoding);
  1677. $strLength = $stringy->length();
  1678. $paddedLength = $strLength + $left + $right;
  1679. if (!$length || $paddedLength <= $strLength) {
  1680. return $stringy;
  1681. }
  1682. $leftPadding = \mb_substr(str_repeat($padStr, ceil($left / $length)), 0,
  1683. $left, $stringy->encoding);
  1684. $rightPadding = \mb_substr(str_repeat($padStr, ceil($right / $length)),
  1685. 0, $right, $stringy->encoding);
  1686. $stringy->str = $leftPadding . $stringy->str . $rightPadding;
  1687. return $stringy;
  1688. }
  1689. /**
  1690. * Returns true if $str matches the supplied pattern, false otherwise.
  1691. *
  1692. * @param string $pattern Regex pattern to match against
  1693. * @return bool Whether or not $str matches the pattern
  1694. */
  1695. protected function matchesPattern($pattern)
  1696. {
  1697. $regexEncoding = $this->regexEncoding();
  1698. $this->regexEncoding($this->encoding);
  1699. $match = \mb_ereg_match($pattern, $this->str);
  1700. $this->regexEncoding($regexEncoding);
  1701. return $match;
  1702. }
  1703. /**
  1704. * Alias for mb_ereg_replace with a fallback to preg_replace if the
  1705. * mbstring module is not installed.
  1706. */
  1707. protected function eregReplace($pattern, $replacement, $string, $option = 'msr')
  1708. {
  1709. static $functionExists;
  1710. if ($functionExists === null) {
  1711. $functionExists = function_exists('\mb_split');
  1712. }
  1713. if ($functionExists) {
  1714. return \mb_ereg_replace($pattern, $replacement, $string, $option);
  1715. } else if ($this->supportsEncoding()) {
  1716. $option = str_replace('r', '', $option);
  1717. return \preg_replace("/$pattern/u$option", $replacement, $string);
  1718. }
  1719. }
  1720. /**
  1721. * Alias for mb_regex_encoding which default to a noop if the mbstring
  1722. * module is not installed.
  1723. */
  1724. protected function regexEncoding()
  1725. {
  1726. static $functionExists;
  1727. if ($functionExists === null) {
  1728. $functionExists = function_exists('\mb_regex_encoding');
  1729. }
  1730. if ($functionExists) {
  1731. $args = func_get_args();
  1732. return call_user_func_array('\mb_regex_encoding', $args);
  1733. }
  1734. }
  1735. protected function supportsEncoding()
  1736. {
  1737. $supported = ['UTF-8' => true, 'ASCII' => true];
  1738. if (isset($supported[$this->encoding])) {
  1739. return true;
  1740. } else {
  1741. throw new \RuntimeException('Stringy method requires the ' .
  1742. 'mbstring module for encodings other than ASCII and UTF-8. ' .
  1743. 'Encoding used: ' . $this->encoding);
  1744. }
  1745. }
  1746. }