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

/system/classes/kohana/text.php

https://bitbucket.org/seyar/parshin.local
PHP | 590 lines | 287 code | 71 blank | 232 comment | 31 complexity | adc157edc63545536bef8cd0d1f5790e MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  1. <?php defined('SYSPATH') or die('No direct access allowed.');
  2. /**
  3. * Text helper class. Provides simple methods for working with text.
  4. *
  5. * @package Kohana
  6. * @category Helpers
  7. * @author Kohana Team
  8. * @copyright (c) 2007-2010 Kohana Team
  9. * @license http://kohanaframework.org/license
  10. */
  11. class Kohana_Text {
  12. /**
  13. * @var array number units and text equivalents
  14. */
  15. public static $units = array(
  16. 1000000000 => 'billion',
  17. 1000000 => 'million',
  18. 1000 => 'thousand',
  19. 100 => 'hundred',
  20. 90 => 'ninety',
  21. 80 => 'eighty',
  22. 70 => 'seventy',
  23. 60 => 'sixty',
  24. 50 => 'fifty',
  25. 40 => 'fourty',
  26. 30 => 'thirty',
  27. 20 => 'twenty',
  28. 19 => 'nineteen',
  29. 18 => 'eighteen',
  30. 17 => 'seventeen',
  31. 16 => 'sixteen',
  32. 15 => 'fifteen',
  33. 14 => 'fourteen',
  34. 13 => 'thirteen',
  35. 12 => 'twelve',
  36. 11 => 'eleven',
  37. 10 => 'ten',
  38. 9 => 'nine',
  39. 8 => 'eight',
  40. 7 => 'seven',
  41. 6 => 'six',
  42. 5 => 'five',
  43. 4 => 'four',
  44. 3 => 'three',
  45. 2 => 'two',
  46. 1 => 'one',
  47. );
  48. /**
  49. * Limits a phrase to a given number of words.
  50. *
  51. * $text = Text::limit_words($text);
  52. *
  53. * @param string phrase to limit words of
  54. * @param integer number of words to limit to
  55. * @param string end character or entity
  56. * @return string
  57. */
  58. public static function limit_words($str, $limit = 100, $end_char = NULL)
  59. {
  60. $limit = (int) $limit;
  61. $end_char = ($end_char === NULL) ? '…' : $end_char;
  62. if (trim($str) === '')
  63. return $str;
  64. if ($limit <= 0)
  65. return $end_char;
  66. preg_match('/^\s*+(?:\S++\s*+){1,'.$limit.'}/u', $str, $matches);
  67. // Only attach the end character if the matched string is shorter
  68. // than the starting string.
  69. return rtrim($matches[0]).((strlen($matches[0]) === strlen($str)) ? '' : $end_char);
  70. }
  71. /**
  72. * Limits a phrase to a given number of characters.
  73. *
  74. * $text = Text::limit_chars($text);
  75. *
  76. * @param string phrase to limit characters of
  77. * @param integer number of characters to limit to
  78. * @param string end character or entity
  79. * @param boolean enable or disable the preservation of words while limiting
  80. * @return string
  81. * @uses UTF8::strlen
  82. */
  83. public static function limit_chars($str, $limit = 100, $end_char = NULL, $preserve_words = FALSE)
  84. {
  85. $end_char = ($end_char === NULL) ? '…' : $end_char;
  86. $limit = (int) $limit;
  87. if (trim($str) === '' OR UTF8::strlen($str) <= $limit)
  88. return $str;
  89. if ($limit <= 0)
  90. return $end_char;
  91. if ($preserve_words === FALSE)
  92. return rtrim(UTF8::substr($str, 0, $limit)).$end_char;
  93. // Don't preserve words. The limit is considered the top limit.
  94. // No strings with a length longer than $limit should be returned.
  95. if ( ! preg_match('/^.{0,'.$limit.'}\s/us', $str, $matches))
  96. return $end_char;
  97. return rtrim($matches[0]).((strlen($matches[0]) === strlen($str)) ? '' : $end_char);
  98. }
  99. /**
  100. * Alternates between two or more strings.
  101. *
  102. * echo Text::alternate('one', 'two'); // "one"
  103. * echo Text::alternate('one', 'two'); // "two"
  104. * echo Text::alternate('one', 'two'); // "one"
  105. *
  106. * Note that using multiple iterations of different strings may produce
  107. * unexpected results.
  108. *
  109. * @param string strings to alternate between
  110. * @return string
  111. */
  112. public static function alternate()
  113. {
  114. static $i;
  115. if (func_num_args() === 0)
  116. {
  117. $i = 0;
  118. return '';
  119. }
  120. $args = func_get_args();
  121. return $args[($i++ % count($args))];
  122. }
  123. /**
  124. * Generates a random string of a given type and length.
  125. *
  126. *
  127. * $str = Text::random(); // 8 character random string
  128. *
  129. * The following types are supported:
  130. *
  131. * alnum
  132. * : Upper and lower case a-z, 0-9 (default)
  133. *
  134. * alpha
  135. * : Upper and lower case a-z
  136. *
  137. * hexdec
  138. * : Hexadecimal characters a-f, 0-9
  139. *
  140. * distinct
  141. * : Uppercase characters and numbers that cannot be confused
  142. *
  143. * You can also create a custom type by providing the "pool" of characters
  144. * as the type.
  145. *
  146. * @param string a type of pool, or a string of characters to use as the pool
  147. * @param integer length of string to return
  148. * @return string
  149. * @uses UTF8::split
  150. */
  151. public static function random($type = NULL, $length = 8)
  152. {
  153. if ($type === NULL)
  154. {
  155. // Default is to generate an alphanumeric string
  156. $type = 'alnum';
  157. }
  158. $utf8 = FALSE;
  159. switch ($type)
  160. {
  161. case 'alnum':
  162. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  163. break;
  164. case 'alpha':
  165. $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  166. break;
  167. case 'hexdec':
  168. $pool = '0123456789abcdef';
  169. break;
  170. case 'numeric':
  171. $pool = '0123456789';
  172. break;
  173. case 'nozero':
  174. $pool = '123456789';
  175. break;
  176. case 'distinct':
  177. $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
  178. break;
  179. default:
  180. $pool = (string) $type;
  181. $utf8 = ! UTF8::is_ascii($pool);
  182. break;
  183. }
  184. // Split the pool into an array of characters
  185. $pool = ($utf8 === TRUE) ? UTF8::str_split($pool, 1) : str_split($pool, 1);
  186. // Largest pool key
  187. $max = count($pool) - 1;
  188. $str = '';
  189. for ($i = 0; $i < $length; $i++)
  190. {
  191. // Select a random character from the pool and add it to the string
  192. $str .= $pool[mt_rand(0, $max)];
  193. }
  194. // Make sure alnum strings contain at least one letter and one digit
  195. if ($type === 'alnum' AND $length > 1)
  196. {
  197. if (ctype_alpha($str))
  198. {
  199. // Add a random digit
  200. $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57));
  201. }
  202. elseif (ctype_digit($str))
  203. {
  204. // Add a random letter
  205. $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90));
  206. }
  207. }
  208. return $str;
  209. }
  210. /**
  211. * Reduces multiple slashes in a string to single slashes.
  212. *
  213. * $str = Text::reduce_slashes('foo//bar/baz'); // "foo/bar/baz"
  214. *
  215. * @param string string to reduce slashes of
  216. * @return string
  217. */
  218. public static function reduce_slashes($str)
  219. {
  220. return preg_replace('#(?<!:)//+#', '/', $str);
  221. }
  222. /**
  223. * Replaces the given words with a string.
  224. *
  225. * // Displays "What the #####, man!"
  226. * echo Text::censor('What the frick, man!', array(
  227. * 'frick' => '#####',
  228. * ));
  229. *
  230. * @param string phrase to replace words in
  231. * @param array words to replace
  232. * @param string replacement string
  233. * @param boolean replace words across word boundries (space, period, etc)
  234. * @return string
  235. * @uses UTF8::strlen
  236. */
  237. public static function censor($str, $badwords, $replacement = '#', $replace_partial_words = TRUE)
  238. {
  239. foreach ( (array) $badwords as $key => $badword)
  240. {
  241. $badwords[$key] = str_replace('\*', '\S*?', preg_quote( (string) $badword));
  242. }
  243. $regex = '('.implode('|', $badwords).')';
  244. if ($replace_partial_words === FALSE)
  245. {
  246. // Just using \b isn't sufficient when we need to replace a badword that already contains word boundaries itself
  247. $regex = '(?<=\b|\s|^)'.$regex.'(?=\b|\s|$)';
  248. }
  249. $regex = '!'.$regex.'!ui';
  250. if (UTF8::strlen($replacement) == 1)
  251. {
  252. $regex .= 'e';
  253. return preg_replace($regex, 'str_repeat($replacement, UTF8::strlen(\'$1\'))', $str);
  254. }
  255. return preg_replace($regex, $replacement, $str);
  256. }
  257. /**
  258. * Finds the text that is similar between a set of words.
  259. *
  260. * $match = Text::similar(array('fred', 'fran', 'free'); // "fr"
  261. *
  262. * @param array words to find similar text of
  263. * @return string
  264. */
  265. public static function similar(array $words)
  266. {
  267. // First word is the word to match against
  268. $word = current($words);
  269. for ($i = 0, $max = strlen($word); $i < $max; ++$i)
  270. {
  271. foreach ($words as $w)
  272. {
  273. // Once a difference is found, break out of the loops
  274. if ( ! isset($w[$i]) OR $w[$i] !== $word[$i])
  275. break 2;
  276. }
  277. }
  278. // Return the similar text
  279. return substr($word, 0, $i);
  280. }
  281. /**
  282. * Converts text email addresses and anchors into links. Existing links
  283. * will not be altered.
  284. *
  285. * echo Text::auto_link($text);
  286. *
  287. * [!!] This method is not foolproof since it uses regex to parse HTML.
  288. *
  289. * @param string text to auto link
  290. * @return string
  291. * @uses Text::auto_link_urls
  292. * @uses Text::auto_link_emails
  293. */
  294. public static function auto_link($text)
  295. {
  296. // Auto link emails first to prevent problems with "www.domain.com@example.com"
  297. return Text::auto_link_urls(Text::auto_link_emails($text));
  298. }
  299. /**
  300. * Converts text anchors into links. Existing links will not be altered.
  301. *
  302. * echo Text::auto_link_urls($text);
  303. *
  304. * [!!] This method is not foolproof since it uses regex to parse HTML.
  305. *
  306. * @param string text to auto link
  307. * @return string
  308. * @uses HTML::anchor
  309. */
  310. public static function auto_link_urls($text)
  311. {
  312. // Find and replace all http/https/ftp/ftps links that are not part of an existing html anchor
  313. $text = preg_replace_callback('~\b(?<!href="|">)(?:ht|f)tps?://\S+(?:/|\b)~i', 'Text::_auto_link_urls_callback1', $text);
  314. // Find and replace all naked www.links.com (without http://)
  315. return preg_replace_callback('~\b(?<!://|">)www(?:\.[a-z0-9][-a-z0-9]*+)+\.[a-z]{2,6}\b~i', 'Text::_auto_link_urls_callback2', $text);
  316. }
  317. protected static function _auto_link_urls_callback1($matches)
  318. {
  319. return HTML::anchor($matches[0]);
  320. }
  321. protected static function _auto_link_urls_callback2($matches)
  322. {
  323. return HTML::anchor('http://'.$matches[0], $matches[0]);
  324. }
  325. /**
  326. * Converts text email addresses into links. Existing links will not
  327. * be altered.
  328. *
  329. * echo Text::auto_link_emails($text);
  330. *
  331. * [!!] This method is not foolproof since it uses regex to parse HTML.
  332. *
  333. * @param string text to auto link
  334. * @return string
  335. * @uses HTML::mailto
  336. */
  337. public static function auto_link_emails($text)
  338. {
  339. // Find and replace all email addresses that are not part of an existing html mailto anchor
  340. // Note: The "58;" negative lookbehind prevents matching of existing encoded html mailto anchors
  341. // The html entity for a colon (:) is &#58; or &#058; or &#0058; etc.
  342. return preg_replace_callback('~\b(?<!href="mailto:|58;)(?!\.)[-+_a-z0-9.]++(?<!\.)@(?![-.])[-a-z0-9.]+(?<!\.)\.[a-z]{2,6}\b(?!</a>)~i', 'Text::_auto_link_emails_callback', $text);
  343. }
  344. protected static function _auto_link_emails_callback($matches)
  345. {
  346. return HTML::mailto($matches[0]);
  347. }
  348. /**
  349. * Automatically applies "p" and "br" markup to text.
  350. * Basically [nl2br](http://php.net/nl2br) on steroids.
  351. *
  352. * echo Text::auto_p($text);
  353. *
  354. * [!!] This method is not foolproof since it uses regex to parse HTML.
  355. *
  356. * @param string subject
  357. * @param boolean convert single linebreaks to <br />
  358. * @return string
  359. */
  360. public static function auto_p($str, $br = TRUE)
  361. {
  362. // Trim whitespace
  363. if (($str = trim($str)) === '')
  364. return '';
  365. // Standardize newlines
  366. $str = str_replace(array("\r\n", "\r"), "\n", $str);
  367. // Trim whitespace on each line
  368. $str = preg_replace('~^[ \t]+~m', '', $str);
  369. $str = preg_replace('~[ \t]+$~m', '', $str);
  370. // The following regexes only need to be executed if the string contains html
  371. if ($html_found = (strpos($str, '<') !== FALSE))
  372. {
  373. // Elements that should not be surrounded by p tags
  374. $no_p = '(?:p|div|h[1-6r]|ul|ol|li|blockquote|d[dlt]|pre|t[dhr]|t(?:able|body|foot|head)|c(?:aption|olgroup)|form|s(?:elect|tyle)|a(?:ddress|rea)|ma(?:p|th))';
  375. // Put at least two linebreaks before and after $no_p elements
  376. $str = preg_replace('~^<'.$no_p.'[^>]*+>~im', "\n$0", $str);
  377. $str = preg_replace('~</'.$no_p.'\s*+>$~im', "$0\n", $str);
  378. }
  379. // Do the <p> magic!
  380. $str = '<p>'.trim($str).'</p>';
  381. $str = preg_replace('~\n{2,}~', "</p>\n\n<p>", $str);
  382. // The following regexes only need to be executed if the string contains html
  383. if ($html_found !== FALSE)
  384. {
  385. // Remove p tags around $no_p elements
  386. $str = preg_replace('~<p>(?=</?'.$no_p.'[^>]*+>)~i', '', $str);
  387. $str = preg_replace('~(</?'.$no_p.'[^>]*+>)</p>~i', '$1', $str);
  388. }
  389. // Convert single linebreaks to <br />
  390. if ($br === TRUE)
  391. {
  392. $str = preg_replace('~(?<!\n)\n(?!\n)~', "<br />\n", $str);
  393. }
  394. return $str;
  395. }
  396. /**
  397. * Returns human readable sizes. Based on original functions written by
  398. * [Aidan Lister](http://aidanlister.com/repos/v/function.size_readable.php)
  399. * and [Quentin Zervaas](http://www.phpriot.com/d/code/strings/filesize-format/).
  400. *
  401. * echo Text::bytes(filesize($file));
  402. *
  403. * @param integer size in bytes
  404. * @param string a definitive unit
  405. * @param string the return string format
  406. * @param boolean whether to use SI prefixes or IEC
  407. * @return string
  408. */
  409. public static function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE)
  410. {
  411. // Format string
  412. $format = ($format === NULL) ? '%01.2f %s' : (string) $format;
  413. // IEC prefixes (binary)
  414. if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE)
  415. {
  416. $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
  417. $mod = 1024;
  418. }
  419. // SI prefixes (decimal)
  420. else
  421. {
  422. $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
  423. $mod = 1000;
  424. }
  425. // Determine unit to use
  426. if (($power = array_search( (string) $force_unit, $units)) === FALSE)
  427. {
  428. $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
  429. }
  430. return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
  431. }
  432. /**
  433. * Format a number to human-readable text.
  434. *
  435. * // Display: one thousand and twenty-four
  436. * echo Text::number(1024);
  437. *
  438. * // Display: five million, six hundred and thirty-two
  439. * echo Text::number(5000632);
  440. *
  441. * @param integer number to format
  442. * @return string
  443. * @since 3.0.8
  444. */
  445. public static function number($number)
  446. {
  447. // The number must always be an integer
  448. $number = (int) $number;
  449. // Uncompiled text version
  450. $text = array();
  451. // Last matched unit within the loop
  452. $last_unit = NULL;
  453. // The last matched item within the loop
  454. $last_item = '';
  455. foreach (Text::$units as $unit => $name)
  456. {
  457. if ($number / $unit >= 1)
  458. {
  459. // $value = the number of times the number is divisble by unit
  460. $number -= $unit * ($value = (int) floor($number / $unit));
  461. // Temporary var for textifying the current unit
  462. $item = '';
  463. if ($unit < 100)
  464. {
  465. if ($last_unit < 100 AND $last_unit >= 20)
  466. {
  467. $last_item .= '-'.$name;
  468. }
  469. else
  470. {
  471. $item = $name;
  472. }
  473. }
  474. else
  475. {
  476. $item = Text::number($value).' '.$name;
  477. }
  478. // In the situation that we need to make a composite number (i.e. twenty-three)
  479. // then we need to modify the previous entry
  480. if (empty($item))
  481. {
  482. array_pop($text);
  483. $item = $last_item;
  484. }
  485. $last_item = $text[] = $item;
  486. $last_unit = $unit;
  487. }
  488. }
  489. if (count($text) > 1)
  490. {
  491. $and = array_pop($text);
  492. }
  493. $text = implode(', ', $text);
  494. if (isset($and))
  495. {
  496. $text .= ' and '.$and;
  497. }
  498. return $text;
  499. }
  500. /**
  501. * Prevents [widow words](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin)
  502. * by inserting a non-breaking space between the last two words.
  503. *
  504. * echo Text::widont($text);
  505. *
  506. * @param string text to remove widows from
  507. * @return string
  508. */
  509. public static function widont($str)
  510. {
  511. $str = rtrim($str);
  512. $space = strrpos($str, ' ');
  513. if ($space !== FALSE)
  514. {
  515. $str = substr($str, 0, $space).'&nbsp;'.substr($str, $space + 1);
  516. }
  517. return $str;
  518. }
  519. } // End text