PageRenderTime 248ms CodeModel.GetById 120ms app.highlight 20ms RepoModel.GetById 101ms app.codeStats 0ms

/system/helpers/text_helper.php

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