Text.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. <?php
  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) Kohana Team
  9. * @license https://koseven.ga/LICENSE.md
  10. */
  11. class Kohana_Text {
  12. /**
  13. * @var array number units and text equivalents
  14. */
  15. public static $units = [
  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 => 'forty',
  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 $str phrase to limit words of
  54. * @param integer $limit number of words to limit to
  55. * @param string $end_char 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 $str phrase to limit characters of
  77. * @param integer $limit number of characters to limit to
  78. * @param string $end_char end character or entity
  79. * @param boolean $preserve_words 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 $str,... 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 $type a type of pool, or a string of characters to use as the pool
  147. * @param integer $length 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[random_int(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[random_int(0, $length - 1)] = chr(random_int(48, 57));
  201. }
  202. elseif (ctype_digit($str))
  203. {
  204. // Add a random letter
  205. $str[random_int(0, $length - 1)] = chr(random_int(65, 90));
  206. }
  207. }
  208. return $str;
  209. }
  210. /**
  211. * Uppercase words that are not separated by spaces, using a custom
  212. * delimiter or the default.
  213. *
  214. * $str = Text::ucfirst('content-type'); // returns "Content-Type"
  215. *
  216. * @param string $string string to transform
  217. * @param string $delimiter delimiter to use
  218. * @uses UTF8::ucfirst
  219. * @return string
  220. */
  221. public static function ucfirst($string, $delimiter = '-')
  222. {
  223. // Put the keys back the Case-Convention expected
  224. return implode($delimiter, array_map('UTF8::ucfirst', explode($delimiter, $string)));
  225. }
  226. /**
  227. * Reduces multiple slashes in a string to single slashes.
  228. *
  229. * $str = Text::reduce_slashes('foo//bar/baz'); // "foo/bar/baz"
  230. *
  231. * @param string $str string to reduce slashes of
  232. * @return string
  233. */
  234. public static function reduce_slashes($str)
  235. {
  236. return preg_replace('#(?<!:)//+#', '/', $str);
  237. }
  238. /**
  239. * Replaces the given words with a string.
  240. *
  241. * // Displays "What the #####, man!"
  242. * echo Text::censor('What the frick, man!', array(
  243. * 'frick' => '#####',
  244. * ));
  245. *
  246. * @param string $str phrase to replace words in
  247. * @param array $badwords words to replace
  248. * @param string $replacement replacement string
  249. * @param boolean $replace_partial_words replace words across word boundaries (space, period, etc)
  250. * @return string
  251. * @uses UTF8::strlen
  252. */
  253. public static function censor($str, $badwords, $replacement = '#', $replace_partial_words = TRUE)
  254. {
  255. foreach ( (array) $badwords as $key => $badword)
  256. {
  257. $badwords[$key] = str_replace('\*', '\S*?', preg_quote( (string) $badword));
  258. }
  259. $regex = '('.implode('|', $badwords).')';
  260. if ($replace_partial_words === FALSE)
  261. {
  262. // Just using \b isn't sufficient when we need to replace a badword that already contains word boundaries itself
  263. $regex = '(?<=\b|\s|^)'.$regex.'(?=\b|\s|$)';
  264. }
  265. $regex = '!'.$regex.'!ui';
  266. // if $replacement is a single character: replace each of the characters of the badword with $replacement
  267. if (UTF8::strlen($replacement) == 1)
  268. {
  269. return preg_replace_callback($regex, function($matches) use ($replacement) {
  270. return str_repeat($replacement, UTF8::strlen($matches[1]));
  271. }, $str);
  272. }
  273. // if $replacement is not a single character, fully replace the badword with $replacement
  274. return preg_replace($regex, $replacement, $str);
  275. }
  276. /**
  277. * Finds the text that is similar between a set of words.
  278. *
  279. * $match = Text::similar(array('fred', 'fran', 'free'); // "fr"
  280. *
  281. * @param array $words words to find similar text of
  282. * @return string
  283. */
  284. public static function similar(array $words)
  285. {
  286. // First word is the word to match against
  287. $word = current($words);
  288. for ($i = 0, $max = strlen($word); $i < $max; ++$i)
  289. {
  290. foreach ($words as $w)
  291. {
  292. // Once a difference is found, break out of the loops
  293. if ( ! isset($w[$i]) OR $w[$i] !== $word[$i])
  294. break 2;
  295. }
  296. }
  297. // Return the similar text
  298. return substr($word, 0, $i);
  299. }
  300. /**
  301. * Converts text email addresses and anchors into links. Existing links
  302. * will not be altered.
  303. *
  304. * echo Text::auto_link($text);
  305. *
  306. * [!!] This method is not foolproof since it uses regex to parse HTML.
  307. *
  308. * @param string $text text to auto link
  309. * @return string
  310. * @uses Text::auto_link_urls
  311. * @uses Text::auto_link_emails
  312. */
  313. public static function auto_link($text)
  314. {
  315. // Auto link emails first to prevent problems with "www.domain.com@example.com"
  316. return Text::auto_link_urls(Text::auto_link_emails($text));
  317. }
  318. /**
  319. * Converts text anchors into links. Existing links will not be altered.
  320. *
  321. * echo Text::auto_link_urls($text);
  322. *
  323. * [!!] This method is not foolproof since it uses regex to parse HTML.
  324. *
  325. * @param string $text text to auto link
  326. * @return string
  327. * @uses HTML::anchor
  328. */
  329. public static function auto_link_urls($text)
  330. {
  331. // Find and replace all http/https/ftp/ftps links that are not part of an existing html anchor
  332. $text = preg_replace_callback('~\b(?<!href="|">)(?:ht|f)tps?://[^<\s]+(?:/|\b)~i', 'Text::_auto_link_urls_callback1', $text);
  333. // Find and replace all naked www.links.com (without http://)
  334. return preg_replace_callback('~\b(?<!://|">)www(?:\.[a-z0-9][-a-z0-9]*+)+\.[a-z]{2,6}[^<\s]*\b~i', 'Text::_auto_link_urls_callback2', $text);
  335. }
  336. protected static function _auto_link_urls_callback1($matches)
  337. {
  338. return HTML::anchor($matches[0]);
  339. }
  340. protected static function _auto_link_urls_callback2($matches)
  341. {
  342. return HTML::anchor('http://'.$matches[0], $matches[0]);
  343. }
  344. /**
  345. * Converts text email addresses into links. Existing links will not
  346. * be altered.
  347. *
  348. * echo Text::auto_link_emails($text);
  349. *
  350. * [!!] This method is not foolproof since it uses regex to parse HTML.
  351. *
  352. * @param string $text text to auto link
  353. * @return string
  354. * @uses HTML::mailto
  355. */
  356. public static function auto_link_emails($text)
  357. {
  358. // Find and replace all email addresses that are not part of an existing html mailto anchor
  359. // Note: The "58;" negative lookbehind prevents matching of existing encoded html mailto anchors
  360. // The html entity for a colon (:) is &#58; or &#058; or &#0058; etc.
  361. 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);
  362. }
  363. protected static function _auto_link_emails_callback($matches)
  364. {
  365. return HTML::mailto($matches[0]);
  366. }
  367. /**
  368. * Automatically applies "p" and "br" markup to text.
  369. * Basically [nl2br](http://php.net/nl2br) on steroids.
  370. *
  371. * echo Text::auto_p($text);
  372. *
  373. * [!!] This method is not foolproof since it uses regex to parse HTML.
  374. *
  375. * @param string $str subject
  376. * @param boolean $br convert single linebreaks to <br />
  377. * @return string
  378. */
  379. public static function auto_p($str, $br = TRUE)
  380. {
  381. // Trim whitespace
  382. if (($str = trim($str)) === '')
  383. return '';
  384. // Standardize newlines
  385. $str = str_replace(["\r\n", "\r"], "\n", $str);
  386. // Trim whitespace on each line
  387. $str = preg_replace('~^[ \t]+~m', '', $str);
  388. $str = preg_replace('~[ \t]+$~m', '', $str);
  389. // The following regexes only need to be executed if the string contains html
  390. if ($html_found = (strpos($str, '<') !== FALSE))
  391. {
  392. // Elements that should not be surrounded by p tags
  393. $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))';
  394. // Put at least two linebreaks before and after $no_p elements
  395. $str = preg_replace('~^<'.$no_p.'[^>]*+>~im', "\n$0", $str);
  396. $str = preg_replace('~</'.$no_p.'\s*+>$~im', "$0\n", $str);
  397. }
  398. // Do the <p> magic!
  399. $str = '<p>'.trim($str).'</p>';
  400. $str = preg_replace('~\n{2,}~', "</p>\n\n<p>", $str);
  401. // The following regexes only need to be executed if the string contains html
  402. if ($html_found !== FALSE)
  403. {
  404. // Remove p tags around $no_p elements
  405. $str = preg_replace('~<p>(?=</?'.$no_p.'[^>]*+>)~i', '', $str);
  406. $str = preg_replace('~(</?'.$no_p.'[^>]*+>)</p>~i', '$1', $str);
  407. }
  408. // Convert single linebreaks to <br />
  409. if ($br === TRUE)
  410. {
  411. $str = preg_replace('~(?<!\n)\n(?!\n)~', "<br />\n", $str);
  412. }
  413. return $str;
  414. }
  415. /**
  416. * Returns human readable sizes. Based on original functions written by
  417. * [Aidan Lister](http://aidanlister.com/repos/v/function.size_readable.php)
  418. * and [Quentin Zervaas](http://www.phpriot.com/d/code/strings/filesize-format/).
  419. *
  420. * echo Text::bytes(filesize($file));
  421. *
  422. * @param integer $bytes size in bytes
  423. * @param string $force_unit a definitive unit
  424. * @param string $format the return string format
  425. * @param boolean $si whether to use SI prefixes or IEC
  426. * @return string
  427. */
  428. public static function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE)
  429. {
  430. // Format string
  431. $format = ($format === NULL) ? '%01.2f %s' : (string) $format;
  432. // IEC prefixes (binary)
  433. if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE)
  434. {
  435. $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
  436. $mod = 1024;
  437. }
  438. // SI prefixes (decimal)
  439. else
  440. {
  441. $units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
  442. $mod = 1000;
  443. }
  444. // Determine unit to use
  445. if (($power = array_search( (string) $force_unit, $units)) === FALSE)
  446. {
  447. $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
  448. }
  449. return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
  450. }
  451. /**
  452. * Format a number to human-readable text.
  453. *
  454. * // Display: one thousand and twenty-four
  455. * echo Text::number(1024);
  456. *
  457. * // Display: five million, six hundred and thirty-two
  458. * echo Text::number(5000632);
  459. *
  460. * @param integer $number number to format
  461. * @return string
  462. * @since 3.0.8
  463. */
  464. public static function number($number)
  465. {
  466. // The number must always be an integer
  467. $number = (int) $number;
  468. // Uncompiled text version
  469. $text = [];
  470. // Last matched unit within the loop
  471. $last_unit = NULL;
  472. // The last matched item within the loop
  473. $last_item = '';
  474. foreach (Text::$units as $unit => $name)
  475. {
  476. if ($number / $unit >= 1)
  477. {
  478. // $value = the number of times the number is divisible by unit
  479. $number -= $unit * ($value = (int) floor($number / $unit));
  480. // Temporary var for textifying the current unit
  481. $item = '';
  482. if ($unit < 100)
  483. {
  484. if ($last_unit < 100 AND $last_unit >= 20)
  485. {
  486. $last_item .= '-'.$name;
  487. }
  488. else
  489. {
  490. $item = $name;
  491. }
  492. }
  493. else
  494. {
  495. $item = Text::number($value).' '.$name;
  496. }
  497. // In the situation that we need to make a composite number (i.e. twenty-three)
  498. // then we need to modify the previous entry
  499. if (empty($item))
  500. {
  501. array_pop($text);
  502. $item = $last_item;
  503. }
  504. $last_item = $text[] = $item;
  505. $last_unit = $unit;
  506. }
  507. }
  508. if (count($text) > 1)
  509. {
  510. $and = array_pop($text);
  511. }
  512. $text = implode(', ', $text);
  513. if (isset($and))
  514. {
  515. $text .= ' and '.$and;
  516. }
  517. return $text;
  518. }
  519. /**
  520. * Prevents [widow words](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin)
  521. * by inserting a non-breaking space between the last two words.
  522. *
  523. * echo Text::widont($text);
  524. *
  525. * regex courtesy of the Typogrify project
  526. * @link http://code.google.com/p/typogrify/
  527. *
  528. * @param string $str text to remove widows from
  529. * @return string
  530. */
  531. public static function widont($str)
  532. {
  533. // use '%' as delimiter and 'x' as modifier
  534. $widont_regex = "%
  535. ((?:</?(?:a|em|span|strong|i|b)[^>]*>)|[^<>\s]) # must be proceeded by an approved inline opening or closing tag or a nontag/nonspace
  536. \s+ # the space to replace
  537. ([^<>\s]+ # must be flollowed by non-tag non-space characters
  538. \s* # optional white space!
  539. (</(a|em|span|strong|i|b)>\s*)* # optional closing inline tags with optional white space after each
  540. ((</(p|h[1-6]|li|dt|dd)>)|$)) # end with a closing p, h1-6, li or the end of the string
  541. %x";
  542. return preg_replace($widont_regex, '$1&nbsp;$2', $str);
  543. }
  544. /**
  545. * Returns information about the client user agent.
  546. *
  547. * // Returns "Chrome" when using Google Chrome
  548. * $browser = Text::user_agent($agent, 'browser');
  549. *
  550. * Multiple values can be returned at once by using an array:
  551. *
  552. * // Get the browser and platform with a single call
  553. * $info = Text::user_agent($agent, array('browser', 'platform'));
  554. *
  555. * When using an array for the value, an associative array will be returned.
  556. *
  557. * @param string $agent user_agent
  558. * @param mixed $value array or string to return: browser, version, robot, mobile, platform
  559. * @return mixed requested information, FALSE if nothing is found
  560. * @uses Kohana::$config
  561. */
  562. public static function user_agent($agent, $value)
  563. {
  564. if (is_array($value))
  565. {
  566. $data = [];
  567. foreach ($value as $part)
  568. {
  569. // Add each part to the set
  570. $data[$part] = Text::user_agent($agent, $part);
  571. }
  572. return $data;
  573. }
  574. if ($value === 'browser' OR $value == 'version')
  575. {
  576. // Extra data will be captured
  577. $info = [];
  578. // Load browsers
  579. $browsers = Kohana::$config->load('user_agents')->browser;
  580. foreach ($browsers as $search => $name)
  581. {
  582. if (stripos($agent, $search) !== FALSE)
  583. {
  584. // Set the browser name
  585. $info['browser'] = $name;
  586. if (preg_match('#'.preg_quote($search).'[^0-9.]*+([0-9.][0-9.a-z]*)#i', $agent, $matches))
  587. {
  588. // Set the version number
  589. $info['version'] = $matches[1];
  590. }
  591. else
  592. {
  593. // No version number found
  594. $info['version'] = FALSE;
  595. }
  596. return $info[$value];
  597. }
  598. }
  599. }
  600. else
  601. {
  602. // Load the search group for this type
  603. $group = Kohana::$config->load('user_agents')->$value;
  604. foreach ($group as $search => $name)
  605. {
  606. if (stripos($agent, $search) !== FALSE)
  607. {
  608. // Set the value name
  609. return $name;
  610. }
  611. }
  612. }
  613. // The value requested could not be found
  614. return FALSE;
  615. }
  616. }