str.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php namespace Laravel;
  2. class Str {
  3. /**
  4. * The pluralizer instance.
  5. *
  6. * @var Pluralizer
  7. */
  8. public static $pluralizer;
  9. /**
  10. * Cache application encoding locally to save expensive calls to Config::get().
  11. *
  12. * @var string
  13. */
  14. public static $encoding = null;
  15. /**
  16. * Get the appliction.encoding without needing to request it from Config::get() each time.
  17. *
  18. * @return string
  19. */
  20. protected static function encoding()
  21. {
  22. return static::$encoding ?: static::$encoding = Config::get('application.encoding');
  23. }
  24. /**
  25. * Get the length of a string.
  26. *
  27. * <code>
  28. * // Get the length of a string
  29. * $length = Str::length('Taylor Otwell');
  30. *
  31. * // Get the length of a multi-byte string
  32. * $length = Str::length('Τάχιστη')
  33. * </code>
  34. *
  35. * @param string $value
  36. * @return int
  37. */
  38. public static function length($value)
  39. {
  40. return (MB_STRING) ? mb_strlen($value, static::encoding()) : strlen($value);
  41. }
  42. /**
  43. * Convert a string to lowercase.
  44. *
  45. * <code>
  46. * // Convert a string to lowercase
  47. * $lower = Str::lower('Taylor Otwell');
  48. *
  49. * // Convert a multi-byte string to lowercase
  50. * $lower = Str::lower('Τάχιστη');
  51. * </code>
  52. *
  53. * @param string $value
  54. * @return string
  55. */
  56. public static function lower($value)
  57. {
  58. return (MB_STRING) ? mb_strtolower($value, static::encoding()) : strtolower($value);
  59. }
  60. /**
  61. * Convert a string to uppercase.
  62. *
  63. * <code>
  64. * // Convert a string to uppercase
  65. * $upper = Str::upper('Taylor Otwell');
  66. *
  67. * // Convert a multi-byte string to uppercase
  68. * $upper = Str::upper('Τάχιστη');
  69. * </code>
  70. *
  71. * @param string $value
  72. * @return string
  73. */
  74. public static function upper($value)
  75. {
  76. return (MB_STRING) ? mb_strtoupper($value, static::encoding()) : strtoupper($value);
  77. }
  78. /**
  79. * Convert a string to title case (ucwords equivalent).
  80. *
  81. * <code>
  82. * // Convert a string to title case
  83. * $title = Str::title('taylor otwell');
  84. *
  85. * // Convert a multi-byte string to title case
  86. * $title = Str::title('νωθρού κυνός');
  87. * </code>
  88. *
  89. * @param string $value
  90. * @return string
  91. */
  92. public static function title($value)
  93. {
  94. if (MB_STRING)
  95. {
  96. return mb_convert_case($value, MB_CASE_TITLE, static::encoding());
  97. }
  98. return ucwords(strtolower($value));
  99. }
  100. /**
  101. * Limit the number of characters in a string.
  102. *
  103. * <code>
  104. * // Returns "Tay..."
  105. * echo Str::limit('Taylor Otwell', 3);
  106. *
  107. * // Limit the number of characters and append a custom ending
  108. * echo Str::limit('Taylor Otwell', 3, '---');
  109. * </code>
  110. *
  111. * @param string $value
  112. * @param int $limit
  113. * @param string $end
  114. * @return string
  115. */
  116. public static function limit($value, $limit = 100, $end = '...')
  117. {
  118. if (static::length($value) <= $limit) return $value;
  119. if (MB_STRING)
  120. {
  121. return mb_substr($value, 0, $limit, static::encoding()).$end;
  122. }
  123. return substr($value, 0, $limit).$end;
  124. }
  125. /**
  126. * Limit the number of chracters in a string including custom ending
  127. *
  128. * <code>
  129. * // Returns "Taylor..."
  130. * echo Str::limit_exact('Taylor Otwell', 9);
  131. *
  132. * // Limit the number of characters and append a custom ending
  133. * echo Str::limit_exact('Taylor Otwell', 9, '---');
  134. * </code>
  135. *
  136. * @param string $value
  137. * @param int $limit
  138. * @param string $end
  139. * @return string
  140. */
  141. public static function limit_exact($value, $limit = 100, $end = '...')
  142. {
  143. if (static::length($value) <= $limit) return $value;
  144. $limit -= static::length($end);
  145. return static::limit($value, $limit, $end);
  146. }
  147. /**
  148. * Limit the number of words in a string.
  149. *
  150. * <code>
  151. * // Returns "This is a..."
  152. * echo Str::words('This is a sentence.', 3);
  153. *
  154. * // Limit the number of words and append a custom ending
  155. * echo Str::words('This is a sentence.', 3, '---');
  156. * </code>
  157. *
  158. * @param string $value
  159. * @param int $words
  160. * @param string $end
  161. * @return string
  162. */
  163. public static function words($value, $words = 100, $end = '...')
  164. {
  165. if (trim($value) == '') return '';
  166. preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
  167. if (static::length($value) == static::length($matches[0]))
  168. {
  169. $end = '';
  170. }
  171. return rtrim($matches[0]).$end;
  172. }
  173. /**
  174. * Get the singular form of the given word.
  175. *
  176. * @param string $value
  177. * @return string
  178. */
  179. public static function singular($value)
  180. {
  181. return static::pluralizer()->singular($value);
  182. }
  183. /**
  184. * Get the plural form of the given word.
  185. *
  186. * <code>
  187. * // Returns the plural form of "child"
  188. * $plural = Str::plural('child', 10);
  189. *
  190. * // Returns the singular form of "octocat" since count is one
  191. * $plural = Str::plural('octocat', 1);
  192. * </code>
  193. *
  194. * @param string $value
  195. * @param int $count
  196. * @return string
  197. */
  198. public static function plural($value, $count = 2)
  199. {
  200. return static::pluralizer()->plural($value, $count);
  201. }
  202. /**
  203. * Get the pluralizer instance.
  204. *
  205. * @return Pluralizer
  206. */
  207. protected static function pluralizer()
  208. {
  209. $config = Config::get('strings');
  210. return static::$pluralizer ?: static::$pluralizer = new Pluralizer($config);
  211. }
  212. /**
  213. * Generate a URL friendly "slug" from a given string.
  214. *
  215. * <code>
  216. * // Returns "this-is-my-blog-post"
  217. * $slug = Str::slug('This is my blog post!');
  218. *
  219. * // Returns "this_is_my_blog_post"
  220. * $slug = Str::slug('This is my blog post!', '_');
  221. * </code>
  222. *
  223. * @param string $title
  224. * @param string $separator
  225. * @return string
  226. */
  227. public static function slug($title, $separator = '-')
  228. {
  229. $title = static::ascii($title);
  230. // Remove all characters that are not the separator, letters, numbers, or whitespace.
  231. $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));
  232. // Replace all separator characters and whitespace by a single separator
  233. $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
  234. return trim($title, $separator);
  235. }
  236. /**
  237. * Convert a string to 7-bit ASCII.
  238. *
  239. * This is helpful for converting UTF-8 strings for usage in URLs, etc.
  240. *
  241. * @param string $value
  242. * @return string
  243. */
  244. public static function ascii($value)
  245. {
  246. $foreign = Config::get('strings.ascii');
  247. $value = preg_replace(array_keys($foreign), array_values($foreign), $value);
  248. return preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '', $value);
  249. }
  250. /**
  251. * Convert a string to an underscored, camel-cased class name.
  252. *
  253. * This method is primarily used to format task and controller names.
  254. *
  255. * <code>
  256. * // Returns "Task_Name"
  257. * $class = Str::classify('task_name');
  258. *
  259. * // Returns "Taylor_Otwell"
  260. * $class = Str::classify('taylor otwell')
  261. * </code>
  262. *
  263. * @param string $value
  264. * @return string
  265. */
  266. public static function classify($value)
  267. {
  268. $search = array('_', '-', '.', '/');
  269. return str_replace(' ', '_', static::title(str_replace($search, ' ', $value)));
  270. }
  271. /**
  272. * Return the "URI" style segments in a given string.
  273. *
  274. * @param string $value
  275. * @return array
  276. */
  277. public static function segments($value)
  278. {
  279. return array_diff(explode('/', trim($value, '/')), array(''));
  280. }
  281. /**
  282. * Generate a random alpha or alpha-numeric string.
  283. *
  284. * <code>
  285. * // Generate a 40 character random alpha-numeric string
  286. * echo Str::random(40);
  287. *
  288. * // Generate a 16 character random alphabetic string
  289. * echo Str::random(16, 'alpha');
  290. * <code>
  291. *
  292. * @param int $length
  293. * @param string $type
  294. * @return string
  295. */
  296. public static function random($length, $type = 'alnum')
  297. {
  298. return substr(str_shuffle(str_repeat(static::pool($type), 5)), 0, $length);
  299. }
  300. /**
  301. * Determine if a given string matches a given pattern.
  302. *
  303. * @param string $pattern
  304. * @param string $value
  305. * @return bool
  306. */
  307. public static function is($pattern, $value)
  308. {
  309. // Asterisks are translated into zero-or-more regular expression wildcards
  310. // to make it convenient to check if the URI starts with a given pattern
  311. // such as "library/*". This is only done when not root.
  312. if ($pattern !== '/')
  313. {
  314. $pattern = str_replace('*', '(.*)', $pattern).'\z';
  315. }
  316. else
  317. {
  318. $pattern = '^/$';
  319. }
  320. return preg_match('#'.$pattern.'#', $value);
  321. }
  322. /**
  323. * Get the character pool for a given type of random string.
  324. *
  325. * @param string $type
  326. * @return string
  327. */
  328. protected static function pool($type)
  329. {
  330. switch ($type)
  331. {
  332. case 'alpha':
  333. return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  334. case 'alnum':
  335. return '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  336. default:
  337. throw new \Exception("Invalid random string type [$type].");
  338. }
  339. }
  340. }