PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/fuel/core/classes/str.php

https://bitbucket.org/codeyash/bootstrap
PHP | 416 lines | 213 code | 46 blank | 157 comment | 10 complexity | 3ddfecc43af5f0fe1803b65f4f7d7171 MD5 | raw file
Possible License(s): MIT, Apache-2.0
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.5
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2013 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. /**
  14. * String handling with encoding support
  15. *
  16. * PHP needs to be compiled with --enable-mbstring
  17. * or a fallback without encoding support is used
  18. */
  19. class Str
  20. {
  21. /**
  22. * Truncates a string to the given length. It will optionally preserve
  23. * HTML tags if $is_html is set to true.
  24. *
  25. * @param string $string the string to truncate
  26. * @param int $limit the number of characters to truncate too
  27. * @param string $continuation the string to use to denote it was truncated
  28. * @param bool $is_html whether the string has HTML
  29. * @return string the truncated string
  30. */
  31. public static function truncate($string, $limit, $continuation = '...', $is_html = false)
  32. {
  33. $offset = 0;
  34. $tags = array();
  35. if ($is_html)
  36. {
  37. // Handle special characters.
  38. preg_match_all('/&[a-z]+;/i', strip_tags($string), $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  39. foreach ($matches as $match)
  40. {
  41. if ($match[0][1] >= $limit)
  42. {
  43. break;
  44. }
  45. $limit += (static::length($match[0][0]) - 1);
  46. }
  47. // Handle all the html tags.
  48. preg_match_all('/<[^>]+>([^<]*)/', $string, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  49. foreach ($matches as $match)
  50. {
  51. if($match[0][1] - $offset >= $limit)
  52. {
  53. break;
  54. }
  55. $tag = static::sub(strtok($match[0][0], " \t\n\r\0\x0B>"), 1);
  56. if($tag[0] != '/')
  57. {
  58. $tags[] = $tag;
  59. }
  60. elseif (end($tags) == static::sub($tag, 1))
  61. {
  62. array_pop($tags);
  63. }
  64. $offset += $match[1][1] - $match[0][1];
  65. }
  66. }
  67. $new_string = static::sub($string, 0, $limit = min(static::length($string), $limit + $offset));
  68. $new_string .= (static::length($string) > $limit ? $continuation : '');
  69. $new_string .= (count($tags = array_reverse($tags)) ? '</'.implode('></',$tags).'>' : '');
  70. return $new_string;
  71. }
  72. /**
  73. * Add's _1 to a string or increment the ending number to allow _2, _3, etc
  74. *
  75. * @param string $str required
  76. * @return string
  77. */
  78. public static function increment($str, $first = 1, $separator = '_')
  79. {
  80. preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
  81. return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
  82. }
  83. /**
  84. * Checks wether a string has a precific beginning.
  85. *
  86. * @param string $str string to check
  87. * @param string $start beginning to check for
  88. * @param boolean $ignore_case wether to ignore the case
  89. * @return boolean wether a string starts with a specified beginning
  90. */
  91. public static function starts_with($str, $start, $ignore_case = false)
  92. {
  93. return (bool) preg_match('/^'.preg_quote($start, '/').'/m'.($ignore_case ? 'i' : ''), $str);
  94. }
  95. /**
  96. * Checks wether a string has a precific ending.
  97. *
  98. * @param string $str string to check
  99. * @param string $end ending to check for
  100. * @param boolean $ignore_case wether to ignore the case
  101. * @return boolean wether a string ends with a specified ending
  102. */
  103. public static function ends_with($str, $end, $ignore_case = false)
  104. {
  105. return (bool) preg_match('/'.preg_quote($end, '/').'$/m'.($ignore_case ? 'i' : ''), $str);
  106. }
  107. /**
  108. * substr
  109. *
  110. * @param string $str required
  111. * @param int $start required
  112. * @param int|null $length
  113. * @param string $encoding default UTF-8
  114. * @return string
  115. */
  116. public static function sub($str, $start, $length = null, $encoding = null)
  117. {
  118. $encoding or $encoding = \Fuel::$encoding;
  119. // substr functions don't parse null correctly
  120. $length = is_null($length) ? (function_exists('mb_substr') ? mb_strlen($str, $encoding) : strlen($str)) - $start : $length;
  121. return function_exists('mb_substr')
  122. ? mb_substr($str, $start, $length, $encoding)
  123. : substr($str, $start, $length);
  124. }
  125. /**
  126. * strlen
  127. *
  128. * @param string $str required
  129. * @param string $encoding default UTF-8
  130. * @return int
  131. */
  132. public static function length($str, $encoding = null)
  133. {
  134. $encoding or $encoding = \Fuel::$encoding;
  135. return function_exists('mb_strlen')
  136. ? mb_strlen($str, $encoding)
  137. : strlen($str);
  138. }
  139. /**
  140. * lower
  141. *
  142. * @param string $str required
  143. * @param string $encoding default UTF-8
  144. * @return string
  145. */
  146. public static function lower($str, $encoding = null)
  147. {
  148. $encoding or $encoding = \Fuel::$encoding;
  149. return function_exists('mb_strtolower')
  150. ? mb_strtolower($str, $encoding)
  151. : strtolower($str);
  152. }
  153. /**
  154. * upper
  155. *
  156. * @param string $str required
  157. * @param string $encoding default UTF-8
  158. * @return string
  159. */
  160. public static function upper($str, $encoding = null)
  161. {
  162. $encoding or $encoding = \Fuel::$encoding;
  163. return function_exists('mb_strtoupper')
  164. ? mb_strtoupper($str, $encoding)
  165. : strtoupper($str);
  166. }
  167. /**
  168. * lcfirst
  169. *
  170. * Does not strtoupper first
  171. *
  172. * @param string $str required
  173. * @param string $encoding default UTF-8
  174. * @return string
  175. */
  176. public static function lcfirst($str, $encoding = null)
  177. {
  178. $encoding or $encoding = \Fuel::$encoding;
  179. return function_exists('mb_strtolower')
  180. ? mb_strtolower(mb_substr($str, 0, 1, $encoding), $encoding).
  181. mb_substr($str, 1, mb_strlen($str, $encoding), $encoding)
  182. : lcfirst($str);
  183. }
  184. /**
  185. * ucfirst
  186. *
  187. * Does not strtolower first
  188. *
  189. * @param string $str required
  190. * @param string $encoding default UTF-8
  191. * @return string
  192. */
  193. public static function ucfirst($str, $encoding = null)
  194. {
  195. $encoding or $encoding = \Fuel::$encoding;
  196. return function_exists('mb_strtoupper')
  197. ? mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding).
  198. mb_substr($str, 1, mb_strlen($str, $encoding), $encoding)
  199. : ucfirst($str);
  200. }
  201. /**
  202. * ucwords
  203. *
  204. * First strtolower then ucwords
  205. *
  206. * ucwords normally doesn't strtolower first
  207. * but MB_CASE_TITLE does, so ucwords now too
  208. *
  209. * @param string $str required
  210. * @param string $encoding default UTF-8
  211. * @return string
  212. */
  213. public static function ucwords($str, $encoding = null)
  214. {
  215. $encoding or $encoding = \Fuel::$encoding;
  216. return function_exists('mb_convert_case')
  217. ? mb_convert_case($str, MB_CASE_TITLE, $encoding)
  218. : ucwords(strtolower($str));
  219. }
  220. /**
  221. * Creates a random string of characters
  222. *
  223. * @param string the type of string
  224. * @param int the number of characters
  225. * @return string the random string
  226. */
  227. public static function random($type = 'alnum', $length = 16)
  228. {
  229. switch($type)
  230. {
  231. case 'basic':
  232. return mt_rand();
  233. break;
  234. default:
  235. case 'alnum':
  236. case 'numeric':
  237. case 'nozero':
  238. case 'alpha':
  239. case 'distinct':
  240. case 'hexdec':
  241. switch ($type)
  242. {
  243. case 'alpha':
  244. $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  245. break;
  246. default:
  247. case 'alnum':
  248. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  249. break;
  250. case 'numeric':
  251. $pool = '0123456789';
  252. break;
  253. case 'nozero':
  254. $pool = '123456789';
  255. break;
  256. case 'distinct':
  257. $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
  258. break;
  259. case 'hexdec':
  260. $pool = '0123456789abcdef';
  261. break;
  262. }
  263. $str = '';
  264. for ($i=0; $i < $length; $i++)
  265. {
  266. $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
  267. }
  268. return $str;
  269. break;
  270. case 'unique':
  271. return md5(uniqid(mt_rand()));
  272. break;
  273. case 'sha1' :
  274. return sha1(uniqid(mt_rand(), true));
  275. break;
  276. }
  277. }
  278. /**
  279. * Returns a closure that will alternate between the args which to return.
  280. * If you call the closure with false as the arg it will return the value without
  281. * alternating the next time.
  282. *
  283. * @return Closure
  284. */
  285. public static function alternator()
  286. {
  287. // the args are the values to alternate
  288. $args = func_get_args();
  289. return function ($next = true) use ($args)
  290. {
  291. static $i = 0;
  292. return $args[($next ? $i++ : $i) % count($args)];
  293. };
  294. }
  295. /**
  296. * Parse the params from a string using strtr()
  297. *
  298. * @param string string to parse
  299. * @param array params to str_replace
  300. * @return string
  301. */
  302. public static function tr($string, $array = array())
  303. {
  304. if (is_string($string))
  305. {
  306. $tr_arr = array();
  307. foreach ($array as $from => $to)
  308. {
  309. substr($from, 0, 1) !== ':' and $from = ':'.$from;
  310. $tr_arr[$from] = $to;
  311. }
  312. unset($array);
  313. return strtr($string, $tr_arr);
  314. }
  315. else
  316. {
  317. return $string;
  318. }
  319. }
  320. /**
  321. * Check if a string is json encoded
  322. *
  323. * @param string $string string to check
  324. * @return bool
  325. */
  326. public static function is_json($string)
  327. {
  328. json_decode($string);
  329. return json_last_error() === JSON_ERROR_NONE;
  330. }
  331. /**
  332. * Check if a string is a valid XML
  333. *
  334. * @param string $string string to check
  335. * @return bool
  336. */
  337. public static function is_xml($string)
  338. {
  339. if ( ! defined('LIBXML_COMPACT'))
  340. {
  341. throw new \FuelException('libxml is required to use Str::is_xml()');
  342. }
  343. $internal_errors = libxml_use_internal_errors();
  344. libxml_use_internal_errors(true);
  345. $result = simplexml_load_string($string) !== false;
  346. libxml_use_internal_errors($internal_errors);
  347. return $result;
  348. }
  349. /**
  350. * Check if a string is serialized
  351. *
  352. * @param string $string string to check
  353. * @return bool
  354. */
  355. public static function is_serialized($string)
  356. {
  357. $array = @unserialize($string);
  358. return ! ($array === false and $string !== 'b:0;');
  359. }
  360. /**
  361. * Check if a string is html
  362. *
  363. * @param string $string string to check
  364. * @return bool
  365. */
  366. public static function is_html($string)
  367. {
  368. return strlen(strip_tags($string)) < strlen($string);
  369. }
  370. }