PageRenderTime 56ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/system/helpers/text_helper.php

https://github.com/chriskelley/CodeIgniter
PHP | 540 lines | 324 code | 62 blank | 154 comment | 41 complexity | cfe56f55e7ee5e7791409c25a72d9337 MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.2.4 or newer
  6. *
  7. * NOTICE OF LICENSE
  8. *
  9. * Licensed under the Open Software License version 3.0
  10. *
  11. * This source file is subject to the Open Software License (OSL 3.0) that is
  12. * bundled with this package in the files license.txt / license.rst. It is
  13. * also available through the world wide web at this URL:
  14. * http://opensource.org/licenses/OSL-3.0
  15. * If you did not receive a copy of the license and are unable to obtain it
  16. * through the world wide web, please send an email to
  17. * licensing@ellislab.com so we can send you a copy immediately.
  18. *
  19. * @package CodeIgniter
  20. * @author EllisLab Dev Team
  21. * @copyright Copyright (c) 2008 - 2013, EllisLab, Inc. (http://ellislab.com/)
  22. * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
  23. * @link http://codeigniter.com
  24. * @since Version 1.0
  25. * @filesource
  26. */
  27. defined('BASEPATH') OR exit('No direct script access allowed');
  28. /**
  29. * CodeIgniter Text Helpers
  30. *
  31. * @package CodeIgniter
  32. * @subpackage Helpers
  33. * @category Helpers
  34. * @author EllisLab Dev Team
  35. * @link http://codeigniter.com/user_guide/helpers/text_helper.html
  36. */
  37. // ------------------------------------------------------------------------
  38. if ( ! function_exists('word_limiter'))
  39. {
  40. /**
  41. * Word Limiter
  42. *
  43. * Limits a string to X number of words.
  44. *
  45. * @param string
  46. * @param int
  47. * @param string the end character. Usually an ellipsis
  48. * @return string
  49. */
  50. function word_limiter($str, $limit = 100, $end_char = '&#8230;')
  51. {
  52. if (trim($str) === '')
  53. {
  54. return $str;
  55. }
  56. preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
  57. if (strlen($str) === strlen($matches[0]))
  58. {
  59. $end_char = '';
  60. }
  61. return rtrim($matches[0]).$end_char;
  62. }
  63. }
  64. // ------------------------------------------------------------------------
  65. if ( ! function_exists('character_limiter'))
  66. {
  67. /**
  68. * Character Limiter
  69. *
  70. * Limits the string based on the character count. Preserves complete words
  71. * so the character count may not be exactly as specified.
  72. *
  73. * @param string
  74. * @param int
  75. * @param string the end character. Usually an ellipsis
  76. * @return string
  77. */
  78. function character_limiter($str, $n = 500, $end_char = '&#8230;')
  79. {
  80. if (strlen($str) < $n)
  81. {
  82. return $str;
  83. }
  84. // a bit complicated, but faster than preg_replace with \s+
  85. $str = preg_replace('/ {2,}/', ' ', str_replace(array("\r", "\n", "\t", "\x0B", "\x0C"), ' ', $str));
  86. if (strlen($str) <= $n)
  87. {
  88. return $str;
  89. }
  90. $out = '';
  91. foreach (explode(' ', trim($str)) as $val)
  92. {
  93. $out .= $val.' ';
  94. if (strlen($out) >= $n)
  95. {
  96. $out = trim($out);
  97. return (strlen($out) === strlen($str)) ? $out : $out.$end_char;
  98. }
  99. }
  100. }
  101. }
  102. // ------------------------------------------------------------------------
  103. if ( ! function_exists('ascii_to_entities'))
  104. {
  105. /**
  106. * High ASCII to Entities
  107. *
  108. * Converts high ASCII text and MS Word special characters to character entities
  109. *
  110. * @param string $str
  111. * @return string
  112. */
  113. function ascii_to_entities($str)
  114. {
  115. $out = '';
  116. for ($i = 0, $s = strlen($str), $count = 1, $temp = array(); $i < $s; $i++)
  117. {
  118. $ordinal = ord($str[$i]);
  119. if ($ordinal < 128)
  120. {
  121. /*
  122. If the $temp array has a value but we have moved on, then it seems only
  123. fair that we output that entity and restart $temp before continuing. -Paul
  124. */
  125. if (count($temp) === 1)
  126. {
  127. $out .= '&#'.array_shift($temp).';';
  128. $count = 1;
  129. }
  130. $out .= $str[$i];
  131. }
  132. else
  133. {
  134. if (count($temp) === 0)
  135. {
  136. $count = ($ordinal < 224) ? 2 : 3;
  137. }
  138. $temp[] = $ordinal;
  139. if (count($temp) === $count)
  140. {
  141. $number = ($count === 3)
  142. ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64)
  143. : (($temp[0] % 32) * 64) + ($temp[1] % 64);
  144. $out .= '&#'.$number.';';
  145. $count = 1;
  146. $temp = array();
  147. }
  148. }
  149. }
  150. return $out;
  151. }
  152. }
  153. // ------------------------------------------------------------------------
  154. if ( ! function_exists('entities_to_ascii'))
  155. {
  156. /**
  157. * Entities to ASCII
  158. *
  159. * Converts character entities back to ASCII
  160. *
  161. * @param string
  162. * @param bool
  163. * @return string
  164. */
  165. function entities_to_ascii($str, $all = TRUE)
  166. {
  167. if (preg_match_all('/\&#(\d+)\;/', $str, $matches))
  168. {
  169. for ($i = 0, $s = count($matches[0]); $i < $s; $i++)
  170. {
  171. $digits = $matches[1][$i];
  172. $out = '';
  173. if ($digits < 128)
  174. {
  175. $out .= chr($digits);
  176. }
  177. elseif ($digits < 2048)
  178. {
  179. $out .= chr(192 + (($digits - ($digits % 64)) / 64)).chr(128 + ($digits % 64));
  180. }
  181. else
  182. {
  183. $out .= chr(224 + (($digits - ($digits % 4096)) / 4096))
  184. .chr(128 + ((($digits % 4096) - ($digits % 64)) / 64))
  185. .chr(128 + ($digits % 64));
  186. }
  187. $str = str_replace($matches[0][$i], $out, $str);
  188. }
  189. }
  190. if ($all)
  191. {
  192. return str_replace(array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#45;'),
  193. array('&', '<', '>', '"', "'", '-'),
  194. $str);
  195. }
  196. return $str;
  197. }
  198. }
  199. // ------------------------------------------------------------------------
  200. if ( ! function_exists('word_censor'))
  201. {
  202. /**
  203. * Word Censoring Function
  204. *
  205. * Supply a string and an array of disallowed words and any
  206. * matched words will be converted to #### or to the replacement
  207. * word you've submitted.
  208. *
  209. * @param string the text string
  210. * @param string the array of censoered words
  211. * @param string the optional replacement value
  212. * @return string
  213. */
  214. function word_censor($str, $censored, $replacement = '')
  215. {
  216. if ( ! is_array($censored))
  217. {
  218. return $str;
  219. }
  220. $str = ' '.$str.' ';
  221. // \w, \b and a few others do not match on a unicode character
  222. // set for performance reasons. As a result words like 端ber
  223. // will not match on a word boundary. Instead, we'll assume that
  224. // a bad word will be bookeneded by any of these characters.
  225. $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
  226. foreach ($censored as $badword)
  227. {
  228. if ($replacement !== '')
  229. {
  230. $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/i", "\\1{$replacement}\\3", $str);
  231. }
  232. else
  233. {
  234. $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'", $str);
  235. }
  236. }
  237. return trim($str);
  238. }
  239. }
  240. // ------------------------------------------------------------------------
  241. if ( ! function_exists('highlight_code'))
  242. {
  243. /**
  244. * Code Highlighter
  245. *
  246. * Colorizes code strings
  247. *
  248. * @param string the text string
  249. * @return string
  250. */
  251. function highlight_code($str)
  252. {
  253. /* The highlight string function encodes and highlights
  254. * brackets so we need them to start raw.
  255. *
  256. * Also replace any existing PHP tags to temporary markers
  257. * so they don't accidentally break the string out of PHP,
  258. * and thus, thwart the highlighting.
  259. */
  260. $str = str_replace(array('&lt;', '&gt;', '<?', '?>', '<%', '%>', '\\', '</script>'),
  261. array('<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
  262. $str);
  263. // The highlight_string function requires that the text be surrounded
  264. // by PHP tags, which we will remove later
  265. $str = highlight_string('<?php '.$str.' ?>', TRUE);
  266. // Remove our artificially added PHP, and the syntax highlighting that came with it
  267. $str = preg_replace(array(
  268. '/<span style="color: #([A-Z0-9]+)">&lt;\?php(&nbsp;| )/i',
  269. '/(<span style="color: #[A-Z0-9]+">.*?)\?&gt;<\/span>\n<\/span>\n<\/code>/is',
  270. '/<span style="color: #[A-Z0-9]+"\><\/span>/i'
  271. ),
  272. array(
  273. '<span style="color: #$1">',
  274. "$1</span>\n</span>\n</code>",
  275. ''
  276. ),
  277. $str);
  278. // Replace our markers back to PHP tags.
  279. return str_replace(array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
  280. array('&lt;?', '?&gt;', '&lt;%', '%&gt;', '\\', '&lt;/script&gt;'),
  281. $str);
  282. }
  283. }
  284. // ------------------------------------------------------------------------
  285. if ( ! function_exists('highlight_phrase'))
  286. {
  287. /**
  288. * Phrase Highlighter
  289. *
  290. * Highlights a phrase within a text string
  291. *
  292. * @param string the text string
  293. * @param string the phrase you'd like to highlight
  294. * @param string the openging tag to precede the phrase with
  295. * @param string the closing tag to end the phrase with
  296. * @return string
  297. */
  298. function highlight_phrase($str, $phrase, $tag_open = '<strong>', $tag_close = '</strong>')
  299. {
  300. if ($str === '')
  301. {
  302. return '';
  303. }
  304. if ($phrase !== '')
  305. {
  306. return preg_replace('/('.preg_quote($phrase, '/').')/i', $tag_open.'\\1'.$tag_close, $str);
  307. }
  308. return $str;
  309. }
  310. }
  311. // ------------------------------------------------------------------------
  312. if ( ! function_exists('convert_accented_characters'))
  313. {
  314. /**
  315. * Convert Accented Foreign Characters to ASCII
  316. *
  317. * @param string $str Input string
  318. * @return string
  319. */
  320. function convert_accented_characters($str)
  321. {
  322. static $array_from, $array_to;
  323. if ( ! is_array($array_from))
  324. {
  325. if (file_exists(APPPATH.'config/foreign_chars.php'))
  326. {
  327. include(APPPATH.'config/foreign_chars.php');
  328. }
  329. if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'))
  330. {
  331. include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php');
  332. }
  333. if (empty($foreign_characters) OR ! is_array($foreign_characters))
  334. {
  335. $array_from = array();
  336. $array_to = array();
  337. return $str;
  338. }
  339. $array_from = array_keys($foreign_characters);
  340. $array_to = array_values($foreign_characters);
  341. }
  342. return preg_replace($array_from, $array_to, $str);
  343. }
  344. }
  345. // ------------------------------------------------------------------------
  346. if ( ! function_exists('word_wrap'))
  347. {
  348. /**
  349. * Word Wrap
  350. *
  351. * Wraps text at the specified character. Maintains the integrity of words.
  352. * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
  353. * will URLs.
  354. *
  355. * @param string $str the text string
  356. * @param int $charlim = 76 the number of characters to wrap at
  357. * @return string
  358. */
  359. function word_wrap($str, $charlim = 76)
  360. {
  361. // Set the character limit
  362. if ( ! is_numeric($charlim))
  363. {
  364. $charlim = 76;
  365. }
  366. // Reduce multiple spaces
  367. $str = preg_replace('| +|', ' ', $str);
  368. // Standardize newlines
  369. if (strpos($str, "\r") !== FALSE)
  370. {
  371. $str = str_replace(array("\r\n", "\r"), "\n", $str);
  372. }
  373. // If the current word is surrounded by {unwrap} tags we'll
  374. // strip the entire chunk and replace it with a marker.
  375. $unwrap = array();
  376. if (preg_match_all('|(\{unwrap\}.+?\{/unwrap\})|s', $str, $matches))
  377. {
  378. for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
  379. {
  380. $unwrap[] = $matches[1][$i];
  381. $str = str_replace($matches[1][$i], '{{unwrapped'.$i.'}}', $str);
  382. }
  383. }
  384. // Use PHP's native function to do the initial wordwrap.
  385. // We set the cut flag to FALSE so that any individual words that are
  386. // too long get left alone. In the next step we'll deal with them.
  387. $str = wordwrap($str, $charlim, "\n", FALSE);
  388. // Split the string into individual lines of text and cycle through them
  389. $output = '';
  390. foreach (explode("\n", $str) as $line)
  391. {
  392. // Is the line within the allowed character count?
  393. // If so we'll join it to the output and continue
  394. if (strlen($line) <= $charlim)
  395. {
  396. $output .= $line."\n";
  397. continue;
  398. }
  399. $temp = '';
  400. while ((strlen($line)) > $charlim)
  401. {
  402. // If the over-length word is a URL we won't wrap it
  403. if (preg_match('!\[url.+\]|://|wwww.!', $line))
  404. {
  405. break;
  406. }
  407. // Trim the word down
  408. $temp .= substr($line, 0, $charlim - 1);
  409. $line = substr($line, $charlim - 1);
  410. }
  411. // If $temp contains data it means we had to split up an over-length
  412. // word into smaller chunks so we'll add it back to our current line
  413. if ($temp !== '')
  414. {
  415. $output .= $temp."\n".$line."\n";
  416. }
  417. else
  418. {
  419. $output .= $line."\n";
  420. }
  421. }
  422. // Put our markers back
  423. if (count($unwrap) > 0)
  424. {
  425. foreach ($unwrap as $key => $val)
  426. {
  427. $output = str_replace('{{unwrapped'.$key.'}}', $val, $output);
  428. }
  429. }
  430. // Remove the unwrap tags and return
  431. return str_replace(array('{unwrap}', '{/unwrap}'), '', $output);
  432. }
  433. }
  434. // ------------------------------------------------------------------------
  435. if ( ! function_exists('ellipsize'))
  436. {
  437. /**
  438. * Ellipsize String
  439. *
  440. * This function will strip tags from a string, split it at its max_length and ellipsize
  441. *
  442. * @param string string to ellipsize
  443. * @param int max length of string
  444. * @param mixed int (1|0) or float, .5, .2, etc for position to split
  445. * @param string ellipsis ; Default '...'
  446. * @return string ellipsized string
  447. */
  448. function ellipsize($str, $max_length, $position = 1, $ellipsis = '&hellip;')
  449. {
  450. // Strip tags
  451. $str = trim(strip_tags($str));
  452. // Is the string long enough to ellipsize?
  453. if (strlen($str) <= $max_length)
  454. {
  455. return $str;
  456. }
  457. $beg = substr($str, 0, floor($max_length * $position));
  458. $position = ($position > 1) ? 1 : $position;
  459. if ($position === 1)
  460. {
  461. $end = substr($str, 0, -($max_length - strlen($beg)));
  462. }
  463. else
  464. {
  465. $end = substr($str, -($max_length - strlen($beg)));
  466. }
  467. return $beg.$ellipsis.$end;
  468. }
  469. }
  470. /* End of file text_helper.php */
  471. /* Location: ./system/helpers/text_helper.php */