PageRenderTime 355ms CodeModel.GetById 149ms app.highlight 19ms RepoModel.GetById 182ms app.codeStats 0ms

/system/helpers/text_helper.php

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