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