summaryrefslogtreecommitdiffstats
path: root/system/helpers/typography_helper.php
blob: 6a5495239efbd0b4c18f7691f6f9144caa062674 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Code Igniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package		CodeIgniter
 * @author		Rick Ellis
 * @copyright	Copyright (c) 2006, pMachine, Inc.
 * @license		http://www.codeignitor.com/user_guide/license.html 
 * @link		http://www.codeigniter.com
 * @since		Version 1.0
 * @filesource
 */
 
// ------------------------------------------------------------------------

/**
 * Code Igniter Typography Helpers
 *
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		Rick Ellis
 * @link		http://www.codeigniter.com/user_guide/helpers/typography_helper.html
 */

// ------------------------------------------------------------------------

/**
 * Convert newlines to HTML line breaks except within PRE tags
 *
 * @access	public
 * @param	string
 * @return	string
 */	
function nl2br_except_pre($str)
{
	$ex = explode("pre>",$str);
	$ct = count($ex);
	
	$newstr = "";
	for ($i = 0; $i < $ct; $i++)
	{
		if (($i % 2) == 0)
		{
			$newstr .= nl2br($ex[$i]);
		}
		else 
		{
			$newstr .= $ex[$i];
		}
		
		if ($ct - 1 != $i) 
			$newstr .= "pre>";
	}
	
	return $newstr;
}
	
// ------------------------------------------------------------------------

/**
 * Auto Typography Wrapper Function
 * 
 *
 * @access	public
 * @parm	string
 * @return	string
 */
function auto_typography($str)
{
	$TYPE = new Auto_typography();
	return $TYPE->convert($str);
}
	
// ------------------------------------------------------------------------

/**
 * Auto Typography Class
 * 
 *
 * @access		private
 * @category	Helpers
 * @author		Rick Ellis
 * @author		Paul Burdick
 * @link		http://www.codeigniter.com/user_guide/helpers/
 */
class Auto_typography {

	// Block level elements that should not be wrapped inside <p> tags
	var $block_elements = 'div|blockquote|pre|code|h\d|script|ol|un';
	
	// Elements that should not have <p> and <br /> tags within them.
	var $skip_elements	= 'pre|ol|ul';
	
	// Tags we want the parser to completely ignore when splitting the string.
	var $ignore_elements = 'a|b|i|em|strong|span|img|li';	


	/**
	 * Main Processing Function
	 *
	 */
	function convert($str)
	{
		if ($str == '')
		{
			return '';
		}
		
		$str = ' '.$str.' ';
		
		// Standardize Newlines to make matching easier
		$str = preg_replace("/(\r\n|\r)/", "\n", $str);
		
		/*
		 * Reduce line breaks
		 *
		 * If there are more than two consecutive line 
		 * breaks we'll compress them down to a maximum
		 * of two since there's no benefit to more.
		 *
		 */
		$str = preg_replace("/\n\n+/", "\n\n", $str);

		/*
		 * Convert quotes within tags to tempoarary marker
		 *
		 * We don't want quotes converted within 
		 * tags so we'll temporarily convert them to 
		 * {{{DQ}}} and {{{SQ}}}
		 *
		 */			
		if (preg_match_all("#\<.+?>#si", $str, $matches))
		{
			for ($i = 0; $i < count($matches['0']); $i++)
			{
				$str = str_replace($matches['0'][$i], 
									str_replace(array("'",'"'), array('{{{SQ}}}', '{{{DQ}}}'), $matches['0'][$i]),
									$str);
			}
		}
		
		/*
		 * Convert "ignore" tags to tempoarary marker
		 *
		 * The parser splits out the string at every tag
		 * it encounters.  Certain inline tags, like image 
		 * tags, links, span tags, etc. will be adversely
		 * affected if they are split out so we'll convert
		 * the opening < temporarily to: {{{tag}}}
		 *
		 */			
		$str = preg_replace("#<(/*)(".$this->ignore_elements.")#i", "{{{tag}}}\\1\\2", $str);	
		
		/*
		 * Split the string at every tag
		 *
		 * This creates an array with this prototype:
		 *
		 *	[array]
		 *	{
		 *		[0] = <opening tag>
		 *		[1] = Content contained between the tags
		 *		[2] = <closing tag>
		 *		Etc...
		 *	}
		 *
		 */			
		$chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
		
		/*
		 * Build our finalized string
		 *
		 * We'll cycle through the array, skipping tags,
		 * and processing the contained text
		 *
		 */			
		$str = '';
		$process = TRUE;
		foreach ($chunks as $chunk)
		{
			/*
			 * Are we dealing with a tag?
			 *
			 * If so, we'll skip the processing for this cycle.
			 * Well also set the "process" flag which allows us
			 * to skip <pre> tags and a few other things.
			 *
			 */			
			if (preg_match("#<(/*)(".$this->block_elements.").*?\>#", $chunk, $match)) 
			{
				if (preg_match("#".$this->skip_elements."#", $match['2']))
				{
					$process =  ($match['1'] == '/') ? TRUE : FALSE;		
				}
		
				$str .= $chunk;
				continue;
			}
		
			if ($process == FALSE)
			{
				$str .= $chunk;
				continue;
			}
			
			//  Convert Newlines into <p> and <br /> tags
			$str .= $this->format_newlines($chunk);
		}

		// Convert Quotes and other characters
		$str = $this->format_characters($str);

		//  We'll swap our temporary markers back and do some clean up.
		$str = preg_replace('#(<p>\n*</p>)#', '', $str);
		$str = preg_replace('#(<p.*?>)<p>#', "\\1", $str);
		
		$str = str_replace(
							array('</p></p>', '</p><p>', '{{{tag}}}', '{{{DQ}}}', '{{{SQ}}}'), 
							array('</p>', '<p>', '<', '"', "'"), 
							$str
							);
		
		return trim($str);
	}
	
	// --------------------------------------------------------------------

	/**
	 * Format Characters
	 *
	 * This function mainly converts double and single quotes
	 * to entities, but since these are directional, it does
	 * it based on some rules.  It also converts em-dashes
	 * and a couple other things.
	 */
	function format_characters($str)
	{	
		$table = array(
						' "'		=> " &#8220;",
						'" '		=> "&#8221; ",
						" '"		=> " &#8216;",
						"' "		=> "&#8217; ",
						
						'>"'		=> ">&#8220;",
						'"<'		=> "&#8221;<",
						">'"		=> ">&#8216;",
						"'<"		=> "&#8217;<",

						"\"."		=> "&#8221;.",
						"\","		=> "&#8221;,",
						"\";"		=> "&#8221;;",
						"\":"		=> "&#8221;:",
						"\"!"		=> "&#8221;!",
						"\"?"		=> "&#8221;?",
						
						".  "		=> ".&nbsp; ",
						"?  "		=> "?&nbsp; ",
						"!  "		=> "!&nbsp; ",
						":  "		=> ":&nbsp; ",
					);

		// These deal with quotes within quotes, like:  "'hi here'"
		$start = 0;
		$space = array("\n", "\t", " ");
		
		while(TRUE)
		{
			$current = strpos(substr($str, $start), "\"'");
			
			if ($current === FALSE) break;
			
			$one_before = substr($str, $start+$current-1, 1);
			$one_after = substr($str, $start+$current+2, 1);
			
			if ( ! in_array($one_after, $space) && $one_after != "<")
			{
				$str = str_replace(	$one_before."\"'".$one_after,
									$one_before."&#8220;&#8216;".$one_after,
									$str);
			}
			elseif ( ! in_array($one_before, $space) && (in_array($one_after, $space) OR $one_after == '<'))
			{
				$str = str_replace(	$one_before."\"'".$one_after,
									$one_before."&#8221;&#8217;".$one_after,
									$str);
			}
			
			$start = $start+$current+2;
		}
		
		$start = 0;
		
		while(TRUE)
		{
			$current = strpos(substr($str, $start), "'\"");
			
			if ($current === FALSE) break;
			
			$one_before = substr($str, $start+$current-1, 1);
			$one_after = substr($str, $start+$current+2, 1);
			
			if ( in_array($one_before, $space) && ! in_array($one_after, $space) && $one_after != "<")
			{
				$str = str_replace(	$one_before."'\"".$one_after,
									$one_before."&#8216;&#8220;".$one_after,
									$str);
			}
			elseif ( ! in_array($one_before, $space) && $one_before != ">")
			{
				$str = str_replace(	$one_before."'\"".$one_after,
									$one_before."&#8217;&#8221;".$one_after,
									$str);
			}
			
			$start = $start+$current+2;
		}
		
		// Are there quotes within a word, as in:  ("something")
		if (preg_match_all("/(.)\"(\S+?)\"(.)/", $str, $matches))
		{
			for ($i=0, $s=sizeof($matches['0']); $i < $s; ++$i)
			{
				if ( ! in_array($matches['1'][$i], $space) && ! in_array($matches['3'][$i], $space))
				{
					$str = str_replace(	$matches['0'][$i],
										$matches['1'][$i]."&#8220;".$matches['2'][$i]."&#8221;".$matches['3'][$i],
										$str);
				}
			}
		}
		
		if (preg_match_all("/(.)\'(\S+?)\'(.)/", $str, $matches))
		{
			for ($i=0, $s=sizeof($matches['0']); $i < $s; ++$i)
			{
				if ( ! in_array($matches['1'][$i], $space) && ! in_array($matches['3'][$i], $space))
				{
					$str = str_replace(	$matches['0'][$i],
										$matches['1'][$i]."&#8216;".$matches['2'][$i]."&#8217;".$matches['3'][$i],
										$str);
				}
			}
		}
		
		// How about one apostrophe, as in Rick's
		$start = 0;
		
		while(TRUE)
		{
			$current = strpos(substr($str, $start), "'");
			
			if ($current === FALSE) break;
			
			$one_before = substr($str, $start+$current-1, 1);
			$one_after = substr($str, $start+$current+1, 1);
			
			if ( ! in_array($one_before, $space) && ! in_array($one_after, $space))
			{
				$str = str_replace(	$one_before."'".$one_after,
									$one_before."&#8217;".$one_after,
									$str);
			}
			
			$start = $start+$current+2;
		}

		// Em-dashes
		$start = 0;
		while(TRUE)
		{
			$current = strpos(substr($str, $start), "--");
			
			if ($current === FALSE) break;
			
			$one_before = substr($str, $start+$current-1, 1);
			$one_after = substr($str, $start+$current+2, 1);
			$two_before = substr($str, $start+$current-2, 1);
			$two_after = substr($str, $start+$current+3, 1);
			
			if (( ! in_array($one_before, $space) && ! in_array($one_after, $space))
				OR
				( ! in_array($two_before, $space) && ! in_array($two_after, $space) && $one_before == ' ' && $one_after == ' ')
				)
			{
				$str = str_replace(	$two_before.$one_before."--".$one_after.$two_after,
									$two_before.trim($one_before)."&#8212;".trim($one_after).$two_after,
									$str);
			}
			
			$start = $start+$current+2;
		}
		
		// Ellipsis
		$str = preg_replace("#(\w)\.\.\.(\s|<br />|</p>)#", "\\1&#8230;\\2", $str); 
		$str = preg_replace("#(\s|<br />|</p>)\.\.\.(\w)#", "\\1&#8230;\\2", $str); 
		
		// Run the translation array we defined above		
		$str = str_replace(array_keys($table), array_values($table), $str);
		
		// If there are any stray double quotes we'll catch them here
		
		$start = 0;
		
		while(TRUE)
		{
			$current = strpos(substr($str, $start), '"');
			
			if ($current === FALSE) break;
			
			$one_before = substr($str, $start+$current-1, 1);
			$one_after = substr($str, $start+$current+1, 1);
			
			if ( ! in_array($one_after, $space))
			{
				$str = str_replace(	$one_before.'"'.$one_after,
									$one_before."&#8220;".$one_after,
									$str);
			}
			elseif( ! in_array($one_before, $space))
			{
				$str = str_replace(	$one_before."'".$one_after,
									$one_before."&#8221;".$one_after,
									$str);
			}
			
			$start = $start+$current+2;
		}
		
		$start = 0;
		
		while(TRUE)
		{
			$current = strpos(substr($str, $start), "'");
			
			if ($current === FALSE) break;
			
			$one_before = substr($str, $start+$current-1, 1);
			$one_after = substr($str, $start+$current+1, 1);
			
			if ( ! in_array($one_after, $space))
			{
				$str = str_replace(	$one_before."'".$one_after,
									$one_before."&#8216;".$one_after,
									$str);
			}
			elseif( ! in_array($one_before, $space))
			{
				$str = str_replace(	$one_before."'".$one_after,
									$one_before."&#8217;".$one_after,
									$str);
			}
			
			$start = $start+$current+2;
		}
		
		return $str;
	}
	
	// --------------------------------------------------------------------

	/**
	 * Format Newlines
	 *
	 * Converts newline characters into either <p> tags or <br />
	 *
	 */	
	function format_newlines($str)
	{
		if ($str == '')
		{
			return $str;
		}

		if (strpos($str, "\n") === FALSE)
		{
			return '<p>'.$str.'</p>';
		}
			
		$str = str_replace("\n\n", "</p>\n\n<p>", $str);
		$str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
		
		return '<p>'.$str.'</p>';
	}	
}

 
?>