str.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php namespace Laravel;
  2. class Str {
  3. /**
  4. * Convert a string to lowercase.
  5. *
  6. * @param string $value
  7. * @return string
  8. */
  9. public static function lower($value)
  10. {
  11. if (function_exists('mb_strtolower'))
  12. {
  13. return mb_strtolower($value, static::encoding());
  14. }
  15. return strtolower($value);
  16. }
  17. /**
  18. * Convert a string to uppercase.
  19. *
  20. * @param string $value
  21. * @return string
  22. */
  23. public static function upper($value)
  24. {
  25. if (function_exists('mb_strtoupper'))
  26. {
  27. return mb_strtoupper($value, static::encoding());
  28. }
  29. return strtoupper($value);
  30. }
  31. /**
  32. * Convert a string to title case (ucwords).
  33. *
  34. * @param string $value
  35. * @return string
  36. */
  37. public static function title($value)
  38. {
  39. if (function_exists('mb_convert_case'))
  40. {
  41. return mb_convert_case($value, MB_CASE_TITLE, static::encoding());
  42. }
  43. return ucwords(strtolower($value));
  44. }
  45. /**
  46. * Get the length of a string.
  47. *
  48. * @param string $value
  49. * @return int
  50. */
  51. public static function length($value)
  52. {
  53. if (function_exists('mb_strlen'))
  54. {
  55. return mb_strlen($value, static::encoding());
  56. }
  57. return strlen($value);
  58. }
  59. /**
  60. * Convert a string to 7-bit ASCII.
  61. *
  62. * @param string $value
  63. * @return string
  64. */
  65. public static function ascii($value)
  66. {
  67. $foreign = Config::get('ascii');
  68. $value = preg_replace(array_keys($foreign), array_values($foreign), $value);
  69. return preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '', $value);
  70. }
  71. /**
  72. * Generate a random alpha or alpha-numeric string.
  73. *
  74. * Supported types: 'alpha_num' and 'alpha'.
  75. *
  76. * @param int $length
  77. * @param string $type
  78. * @return string
  79. */
  80. public static function random($length = 16, $type = 'alpha_num')
  81. {
  82. $alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  83. $pool = ($type == 'alpha_num') ? '0123456789'.$alpha : $alpha;
  84. return implode('', array_map(function() use ($pool) { return $pool[mt_rand(0, strlen($pool) - 1)]; }, range(0, $length - 1)));
  85. }
  86. /**
  87. * Get the application encoding from the configuration class.
  88. *
  89. * @return string
  90. */
  91. protected static function encoding()
  92. {
  93. return Config::get('application.encoding');
  94. }
  95. }