text_helper.php 13 KB

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