PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/system/helpers/text_helper.php

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