1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
19 * CodeIgniter Text Helpers
21 * @package CodeIgniter
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/helpers/text_helper.html
28 // ------------------------------------------------------------------------
33 * Limits a string to X number of words.
38 * @param string the end character. Usually an ellipsis
41 if ( ! function_exists('word_limiter'))
43 function word_limiter($str, $limit = 100, $end_char = '…')
50 preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
52 if (strlen($str) == strlen($matches[0]))
57 return rtrim($matches[0]).$end_char;
61 // ------------------------------------------------------------------------
66 * Limits the string based on the character count. Preserves complete words
67 * so the character count may not be exactly as specified.
72 * @param string the end character. Usually an ellipsis
75 if ( ! function_exists('character_limiter'))
77 function character_limiter($str, $n = 500, $end_char = '…')
79 if (strlen($str) < $n)
84 $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
86 if (strlen($str) <= $n)
92 foreach (explode(' ', trim($str)) as $val)
96 if (strlen($out) >= $n)
99 return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
105 // ------------------------------------------------------------------------
108 * High ASCII to Entities
110 * Converts High ascii text and MS Word special characters to character entities
116 if ( ! function_exists('ascii_to_entities'))
118 function ascii_to_entities($str)
124 for ($i = 0, $s = strlen($str); $i < $s; $i++)
126 $ordinal = ord($str[$i]);
131 If the $temp array has a value but we have moved on, then it seems only
132 fair that we output that entity and restart $temp before continuing. -Paul
134 if (count($temp) == 1)
136 $out .= '&#'.array_shift($temp).';';
144 if (count($temp) == 0)
146 $count = ($ordinal < 224) ? 2 : 3;
151 if (count($temp) == $count)
153 $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
155 $out .= '&#'.$number.';';
166 // ------------------------------------------------------------------------
171 * Converts character entities back to ASCII
178 if ( ! function_exists('entities_to_ascii'))
180 function entities_to_ascii($str, $all = TRUE)
182 if (preg_match_all('/\&#(\d+)\;/', $str, $matches))
184 for ($i = 0, $s = count($matches['0']); $i < $s; $i++)
186 $digits = $matches['1'][$i];
192 $out .= chr($digits);
195 elseif ($digits < 2048)
197 $out .= chr(192 + (($digits - ($digits % 64)) / 64));
198 $out .= chr(128 + ($digits % 64));
202 $out .= chr(224 + (($digits - ($digits % 4096)) / 4096));
203 $out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64));
204 $out .= chr(128 + ($digits % 64));
207 $str = str_replace($matches['0'][$i], $out, $str);
213 $str = str_replace(array("&", "<", ">", """, "'", "-"),
214 array("&","<",">","\"", "'", "-"),
222 // ------------------------------------------------------------------------
225 * Word Censoring Function
227 * Supply a string and an array of disallowed words and any
228 * matched words will be converted to #### or to the replacement
229 * word you've submitted.
232 * @param string the text string
233 * @param string the array of censoered words
234 * @param string the optional replacement value
237 if ( ! function_exists('word_censor'))
239 function word_censor($str, $censored, $replacement = '')
241 if ( ! is_array($censored))
248 // \w, \b and a few others do not match on a unicode character
249 // set for performance reasons. As a result words like über
250 // will not match on a word boundary. Instead, we'll assume that
251 // a bad word will be bookeneded by any of these characters.
252 $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
254 foreach ($censored as $badword)
256 if ($replacement != '')
258 $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/i", "\\1{$replacement}\\3", $str);
262 $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'", $str);
270 // ------------------------------------------------------------------------
275 * Colorizes code strings
278 * @param string the text string
281 if ( ! function_exists('highlight_code'))
283 function highlight_code($str)
285 // The highlight string function encodes and highlights
286 // brackets so we need them to start raw
287 $str = str_replace(array('<', '>'), array('<', '>'), $str);
289 // Replace any existing PHP tags to temporary markers so they don't accidentally
290 // break the string out of PHP, and thus, thwart the highlighting.
292 $str = str_replace(array('<?', '?>', '<%', '%>', '\\', '</script>'),
293 array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), $str);
295 // The highlight_string function requires that the text be surrounded
296 // by PHP tags, which we will remove later
297 $str = '<?php '.$str.' ?>'; // <?
299 // All the magic happens here, baby!
300 $str = highlight_string($str, TRUE);
302 // Prior to PHP 5, the highligh function used icky <font> tags
303 // so we'll replace them with <span> tags.
305 if (abs(PHP_VERSION) < 5)
307 $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
308 $str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
311 // Remove our artificially added PHP, and the syntax highlighting that came with it
312 $str = preg_replace('/<span style="color: #([A-Z0-9]+)"><\?php( | )/i', '<span style="color: #$1">', $str);
313 $str = preg_replace('/(<span style="color: #[A-Z0-9]+">.*?)\?><\/span>\n<\/span>\n<\/code>/is', "$1</span>\n</span>\n</code>", $str);
314 $str = preg_replace('/<span style="color: #[A-Z0-9]+"\><\/span>/i', '', $str);
316 // Replace our markers back to PHP tags.
317 $str = str_replace(array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
318 array('<?', '?>', '<%', '%>', '\\', '</script>'), $str);
324 // ------------------------------------------------------------------------
329 * Highlights a phrase within a text string
332 * @param string the text string
333 * @param string the phrase you'd like to highlight
334 * @param string the openging tag to precede the phrase with
335 * @param string the closing tag to end the phrase with
338 if ( ! function_exists('highlight_phrase'))
340 function highlight_phrase($str, $phrase, $tag_open = '<strong>', $tag_close = '</strong>')
349 return preg_replace('/('.preg_quote($phrase, '/').')/i', $tag_open."\\1".$tag_close, $str);
356 // ------------------------------------------------------------------------
359 * Convert Accented Foreign Characters to ASCII
362 * @param string the text string
365 if ( ! function_exists('convert_accented_characters'))
367 function convert_accented_characters($str)
369 if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars'.EXT))
371 include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars'.EXT);
373 elseif (is_file(APPPATH.'config/foreign_chars'.EXT))
375 include(APPPATH.'config/foreign_chars'.EXT);
378 if ( ! isset($foreign_characters))
383 return preg_replace(array_keys($foreign_characters), array_values($foreign_characters), $str);
387 // ------------------------------------------------------------------------
392 * Wraps text at the specified character. Maintains the integrity of words.
393 * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
397 * @param string the text string
398 * @param integer the number of characters to wrap at
401 if ( ! function_exists('word_wrap'))
403 function word_wrap($str, $charlim = '76')
405 // Se the character limit
406 if ( ! is_numeric($charlim))
409 // Reduce multiple spaces
410 $str = preg_replace("| +|", " ", $str);
412 // Standardize newlines
413 if (strpos($str, "\r") !== FALSE)
415 $str = str_replace(array("\r\n", "\r"), "\n", $str);
418 // If the current word is surrounded by {unwrap} tags we'll
419 // strip the entire chunk and replace it with a marker.
421 if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
423 for ($i = 0; $i < count($matches['0']); $i++)
425 $unwrap[] = $matches['1'][$i];
426 $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
430 // Use PHP's native function to do the initial wordwrap.
431 // We set the cut flag to FALSE so that any individual words that are
432 // too long get left alone. In the next step we'll deal with them.
433 $str = wordwrap($str, $charlim, "\n", FALSE);
435 // Split the string into individual lines of text and cycle through them
437 foreach (explode("\n", $str) as $line)
439 // Is the line within the allowed character count?
440 // If so we'll join it to the output and continue
441 if (strlen($line) <= $charlim)
443 $output .= $line."\n";
448 while ((strlen($line)) > $charlim)
450 // If the over-length word is a URL we won't wrap it
451 if (preg_match("!\[url.+\]|://|wwww.!", $line))
456 // Trim the word down
457 $temp .= substr($line, 0, $charlim-1);
458 $line = substr($line, $charlim-1);
461 // If $temp contains data it means we had to split up an over-length
462 // word into smaller chunks so we'll add it back to our current line
465 $output .= $temp."\n".$line;
475 // Put our markers back
476 if (count($unwrap) > 0)
478 foreach ($unwrap as $key => $val)
480 $output = str_replace("{{unwrapped".$key."}}", $val, $output);
484 // Remove the unwrap tags
485 $output = str_replace(array('{unwrap}', '{/unwrap}'), '', $output);
491 // ------------------------------------------------------------------------
496 * This function will strip tags from a string, split it at its max_length and ellipsize
498 * @param string string to ellipsize
499 * @param integer max length of string
500 * @param mixed int (1|0) or float, .5, .2, etc for position to split
501 * @param string ellipsis ; Default '...'
502 * @return string ellipsized string
504 if ( ! function_exists('ellipsize'))
506 function ellipsize($str, $max_length, $position = 1, $ellipsis = '…')
509 $str = trim(strip_tags($str));
511 // Is the string long enough to ellipsize?
512 if (strlen($str) <= $max_length)
517 $beg = substr($str, 0, floor($max_length * $position));
519 $position = ($position > 1) ? 1 : $position;
523 $end = substr($str, 0, -($max_length - strlen($beg)));
527 $end = substr($str, -($max_length - strlen($beg)));
530 return $beg.$ellipsis.$end;
534 /* End of file text_helper.php */
535 /* Location: ./system/helpers/text_helper.php */