PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/helpers/text_helper.php

https://github.com/marcoliverteschke/redesign.marcoliverteschke.de
PHP | 444 lines | 348 code | 27 blank | 69 comment | 23 complexity | 532984af668f2be94b87001d288c8cb5 MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 4.3.2 or newer
  6. *
  7. * @package CodeIgniter
  8. * @author ExpressionEngine Dev Team
  9. * @copyright Copyright (c) 2006, 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. return trim($out).$end_char;
  86. }
  87. }
  88. }
  89. }
  90. // ------------------------------------------------------------------------
  91. /**
  92. * High ASCII to Entities
  93. *
  94. * Converts High ascii text and MS Word special characters to character entities
  95. *
  96. * @access public
  97. * @param string
  98. * @return string
  99. */
  100. if ( ! function_exists('ascii_to_entities'))
  101. {
  102. function ascii_to_entities($str)
  103. {
  104. $count = 1;
  105. $out = '';
  106. $temp = array();
  107. for ($i = 0, $s = strlen($str); $i < $s; $i++)
  108. {
  109. $ordinal = ord($str[$i]);
  110. if ($ordinal < 128)
  111. {
  112. $out .= $str[$i];
  113. }
  114. else
  115. {
  116. if (count($temp) == 0)
  117. {
  118. $count = ($ordinal < 224) ? 2 : 3;
  119. }
  120. $temp[] = $ordinal;
  121. if (count($temp) == $count)
  122. {
  123. $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
  124. $out .= '&#'.$number.';';
  125. $count = 1;
  126. $temp = array();
  127. }
  128. }
  129. }
  130. return $out;
  131. }
  132. }
  133. // ------------------------------------------------------------------------
  134. /**
  135. * Entities to ASCII
  136. *
  137. * Converts character entities back to ASCII
  138. *
  139. * @access public
  140. * @param string
  141. * @param bool
  142. * @return string
  143. */
  144. if ( ! function_exists('entities_to_ascii'))
  145. {
  146. function entities_to_ascii($str, $all = TRUE)
  147. {
  148. if (preg_match_all('/\&#(\d+)\;/', $str, $matches))
  149. {
  150. for ($i = 0, $s = count($matches['0']); $i < $s; $i++)
  151. {
  152. $digits = $matches['1'][$i];
  153. $out = '';
  154. if ($digits < 128)
  155. {
  156. $out .= chr($digits);
  157. }
  158. elseif ($digits < 2048)
  159. {
  160. $out .= chr(192 + (($digits - ($digits % 64)) / 64));
  161. $out .= chr(128 + ($digits % 64));
  162. }
  163. else
  164. {
  165. $out .= chr(224 + (($digits - ($digits % 4096)) / 4096));
  166. $out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64));
  167. $out .= chr(128 + ($digits % 64));
  168. }
  169. $str = str_replace($matches['0'][$i], $out, $str);
  170. }
  171. }
  172. if ($all)
  173. {
  174. $str = str_replace(array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"),
  175. array("&","<",">","\"", "'", "-"),
  176. $str);
  177. }
  178. return $str;
  179. }
  180. }
  181. // ------------------------------------------------------------------------
  182. /**
  183. * Word Censoring Function
  184. *
  185. * Supply a string and an array of disallowed words and any
  186. * matched words will be converted to #### or to the replacement
  187. * word you've submitted.
  188. *
  189. * @access public
  190. * @param string the text string
  191. * @param string the array of censoered words
  192. * @param string the optional replacement value
  193. * @return string
  194. */
  195. if ( ! function_exists('word_censor'))
  196. {
  197. function word_censor($str, $censored, $replacement = '')
  198. {
  199. if ( ! is_array($censored))
  200. {
  201. return $str;
  202. }
  203. $str = ' '.$str.' ';
  204. foreach ($censored as $badword)
  205. {
  206. if ($replacement != '')
  207. {
  208. $str = preg_replace("/\b(".str_replace('\*', '\w*?', preg_quote($badword)).")\b/i", $replacement, $str);
  209. }
  210. else
  211. {
  212. $str = preg_replace("/\b(".str_replace('\*', '\w*?', preg_quote($badword)).")\b/ie", "str_repeat('#', strlen('\\1'))", $str);
  213. }
  214. }
  215. return trim($str);
  216. }
  217. }
  218. // ------------------------------------------------------------------------
  219. /**
  220. * Code Highlighter
  221. *
  222. * Colorizes code strings
  223. *
  224. * @access public
  225. * @param string the text string
  226. * @return string
  227. */
  228. if ( ! function_exists('highlight_code'))
  229. {
  230. function highlight_code($str)
  231. {
  232. // The highlight string function encodes and highlights
  233. // brackets so we need them to start raw
  234. $str = str_replace(array('&lt;', '&gt;'), array('<', '>'), $str);
  235. // Replace any existing PHP tags to temporary markers so they don't accidentally
  236. // break the string out of PHP, and thus, thwart the highlighting.
  237. $str = str_replace(array('<?', '?>', '<%', '%>', '\\', '</script>'),
  238. array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), $str);
  239. // The highlight_string function requires that the text be surrounded
  240. // by PHP tags. Since we don't know if A) the submitted text has PHP tags,
  241. // or B) whether the PHP tags enclose the entire string, we will add our
  242. // own PHP tags around the string along with some markers to make replacement easier later
  243. $str = '<?php tempstart'."\n".$str.'tempend ?>';
  244. // All the magic happens here, baby!
  245. $str = highlight_string($str, TRUE);
  246. // Prior to PHP 5, the highlight function used icky font tags
  247. // so we'll replace them with span tags.
  248. if (abs(phpversion()) < 5)
  249. {
  250. $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
  251. $str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
  252. }
  253. // Remove our artificially added PHP
  254. $str = preg_replace("#\<code\>.+?tempstart\<br />(?:\</span\>)?#is", "<code>\n", $str);
  255. $str = preg_replace("#tempend.+#is", "</span>\n</code>", $str);
  256. // Replace our markers back to PHP tags.
  257. $str = str_replace(array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
  258. array('&lt;?', '?&gt;', '&lt;%', '%&gt;', '\\', '&lt;/script&gt;'), $str);
  259. return $str;
  260. }
  261. }
  262. // ------------------------------------------------------------------------
  263. /**
  264. * Phrase Highlighter
  265. *
  266. * Highlights a phrase within a text string
  267. *
  268. * @access public
  269. * @param string the text string
  270. * @param string the phrase you'd like to highlight
  271. * @param string the openging tag to precede the phrase with
  272. * @param string the closing tag to end the phrase with
  273. * @return string
  274. */
  275. if ( ! function_exists('highlight_phrase'))
  276. {
  277. function highlight_phrase($str, $phrase, $tag_open = '<strong>', $tag_close = '</strong>')
  278. {
  279. if ($str == '')
  280. {
  281. return '';
  282. }
  283. if ($phrase != '')
  284. {
  285. return preg_replace('/('.preg_quote($phrase, '/').')/i', $tag_open."\\1".$tag_close, $str);
  286. }
  287. return $str;
  288. }
  289. }
  290. // ------------------------------------------------------------------------
  291. /**
  292. * Word Wrap
  293. *
  294. * Wraps text at the specified character. Maintains the integrity of words.
  295. * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
  296. * will URLs.
  297. *
  298. * @access public
  299. * @param string the text string
  300. * @param integer the number of characters to wrap at
  301. * @return string
  302. */
  303. if ( ! function_exists('word_wrap'))
  304. {
  305. function word_wrap($str, $charlim = '76')
  306. {
  307. // Se the character limit
  308. if ( ! is_numeric($charlim))
  309. $charlim = 76;
  310. // Reduce multiple spaces
  311. $str = preg_replace("| +|", " ", $str);
  312. // Standardize newlines
  313. if (strpos($str, "\r") !== FALSE)
  314. {
  315. $str = str_replace(array("\r\n", "\r"), "\n", $str);
  316. }
  317. // If the current word is surrounded by {unwrap} tags we'll
  318. // strip the entire chunk and replace it with a marker.
  319. $unwrap = array();
  320. if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
  321. {
  322. for ($i = 0; $i < count($matches['0']); $i++)
  323. {
  324. $unwrap[] = $matches['1'][$i];
  325. $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
  326. }
  327. }
  328. // Use PHP's native function to do the initial wordwrap.
  329. // We set the cut flag to FALSE so that any individual words that are
  330. // too long get left alone. In the next step we'll deal with them.
  331. $str = wordwrap($str, $charlim, "\n", FALSE);
  332. // Split the string into individual lines of text and cycle through them
  333. $output = "";
  334. foreach (explode("\n", $str) as $line)
  335. {
  336. // Is the line within the allowed character count?
  337. // If so we'll join it to the output and continue
  338. if (strlen($line) <= $charlim)
  339. {
  340. $output .= $line."\n";
  341. continue;
  342. }
  343. $temp = '';
  344. while((strlen($line)) > $charlim)
  345. {
  346. // If the over-length word is a URL we won't wrap it
  347. if (preg_match("!\[url.+\]|://|wwww.!", $line))
  348. {
  349. break;
  350. }
  351. // Trim the word down
  352. $temp .= substr($line, 0, $charlim-1);
  353. $line = substr($line, $charlim-1);
  354. }
  355. // If $temp contains data it means we had to split up an over-length
  356. // word into smaller chunks so we'll add it back to our current line
  357. if ($temp != '')
  358. {
  359. $output .= $temp . "\n" . $line;
  360. }
  361. else
  362. {
  363. $output .= $line;
  364. }
  365. $output .= "\n";
  366. }
  367. // Put our markers back
  368. if (count($unwrap) > 0)
  369. {
  370. foreach ($unwrap as $key => $val)
  371. {
  372. $output = str_replace("{{unwrapped".$key."}}", $val, $output);
  373. }
  374. }
  375. // Remove the unwrap tags
  376. $output = str_replace(array('{unwrap}', '{/unwrap}'), '', $output);
  377. return $output;
  378. }
  379. }
  380. /* End of file text_helper.php */
  381. /* Location: ./system/helpers/text_helper.php */