3 * Main WordPress Formatting API.
5 * Handles many functions for formatting output.
11 * Replaces common plain text characters into formatted entities
15 * 'cause today's effort makes it worth tomorrow's "holiday"...
19 * ’cause today’s effort makes it worth tomorrow’s “holiday”…
21 * Code within certain html blocks are skipped.
24 * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
26 * @param string $text The text to be formatted
27 * @return string The string replaced with html entities
29 function wptexturize($text) {
30 global $wp_cockneyreplace;
31 static $static_setup = false, $opening_quote, $closing_quote, $default_no_texturize_tags, $default_no_texturize_shortcodes, $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements;
34 $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
35 $stop = count($textarr);
37 // No need to set up these variables more than once
39 /* translators: opening curly quote */
40 $opening_quote = _x('“', 'opening curly quote');
41 /* translators: closing curly quote */
42 $closing_quote = _x('”', 'closing curly quote');
44 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
45 $default_no_texturize_shortcodes = array('code');
47 // if a plugin has provided an autocorrect array, use it
48 if ( isset($wp_cockneyreplace) ) {
49 $cockney = array_keys($wp_cockneyreplace);
50 $cockneyreplace = array_values($wp_cockneyreplace);
52 $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
53 $cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
56 $static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)'), $cockney);
57 $static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, $closing_quote, ' ™'), $cockneyreplace);
59 $dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/\'(\d)/', '/(\s|\A|[([{<]|")\'/', '/(\d)"/', '/(\d)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/\b(\d+)x(\d+)\b/');
60 $dynamic_replacements = array('’$1','’$1', '$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');
65 // Transform into regexp sub-expression used in _wptexturize_pushpop_element
66 // Must do this everytime in case plugins use these filters in a context sensitive manner
67 $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
68 $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
70 $no_texturize_tags_stack = array();
71 $no_texturize_shortcodes_stack = array();
73 for ( $i = 0; $i < $stop; $i++ ) {
76 if ( !empty($curl) && '<' != $curl[0] && '[' != $curl[0]
77 && empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) {
78 // This is not a tag, nor is the texturization disabled
80 $curl = str_replace($static_characters, $static_replacements, $curl);
81 // regular expressions
82 $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
83 } elseif (!empty($curl)) {
85 * Only call _wptexturize_pushpop_element if first char is correct
89 _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
90 elseif ('[' == $curl[0])
91 _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
94 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
102 * Search for disabled element tags. Push element to stack on tag open and pop
103 * on tag close. Assumes first character of $text is tag opening.
108 * @param string $text Text to check. First character is assumed to be $opening
109 * @param array $stack Array used as stack of opened tag elements
110 * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
111 * @param string $opening Tag opening character, assumed to be 1 character long
112 * @param string $opening Tag closing character
115 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
116 // Check if it is a closing tag -- otherwise assume opening tag
117 if (strncmp($opening . '/', $text, 2)) {
118 // Opening? Check $text+1 against disabled elements
119 if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
121 * This disables texturize until we find a closing tag of our type
122 * (e.g. <pre>) even if there was invalid nesting before that
124 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
125 * "baba" won't be texturize
128 array_push($stack, $matches[1]);
131 // Closing? Check $text+2 against disabled elements
132 $c = preg_quote($closing, '/');
133 if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
134 $last = array_pop($stack);
136 // Make sure it matches the opening tag
137 if ($last != $matches[1])
138 array_push($stack, $last);
144 * Accepts matches array from preg_replace_callback in wpautop() or a string.
146 * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
147 * converted into paragraphs or line-breaks.
151 * @param array|string $matches The array or string
152 * @return string The pre block without paragraph/line-break conversion.
154 function clean_pre($matches) {
155 if ( is_array($matches) )
156 $text = $matches[1] . $matches[2] . "</pre>";
160 $text = str_replace('<br />', '', $text);
161 $text = str_replace('<p>', "\n", $text);
162 $text = str_replace('</p>', '', $text);
168 * Replaces double line-breaks with paragraph elements.
170 * A group of regex replaces used to identify text formatted with newlines and
171 * replace double line-breaks with HTML paragraph tags. The remaining
172 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
177 * @param string $pee The text which has to be formatted.
178 * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
179 * @return string Text which has been converted into correct paragraph tags.
181 function wpautop($pee, $br = 1) {
183 if ( trim($pee) === '' )
185 $pee = $pee . "\n"; // just to make things a little easier, pad the end
186 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
187 // Space things out a little
188 $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
189 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
190 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
191 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
192 if ( strpos($pee, '<object') !== false ) {
193 $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
194 $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
196 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
197 // make paragraphs, including one at the end
198 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
200 foreach ( $pees as $tinkle )
201 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
202 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
203 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
204 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
205 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
206 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
207 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
208 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
209 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
211 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
212 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
213 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
215 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
216 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
217 if (strpos($pee, '<pre') !== false)
218 $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
219 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
225 * Newline preservation help function for wpautop
229 * @param array $matches preg_replace_callback matches array
232 function _autop_newline_preservation_helper( $matches ) {
233 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
237 * Don't auto-p wrap shortcodes that stand alone
239 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
243 * @param string $pee The content.
244 * @return string The filtered content.
246 function shortcode_unautop($pee) {
247 global $shortcode_tags;
249 if ( !empty($shortcode_tags) && is_array($shortcode_tags) ) {
250 $tagnames = array_keys($shortcode_tags);
251 $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
252 $pee = preg_replace('/<p>\\s*?(\\[(' . $tagregexp . ')\\b.*?\\/?\\](?:.+?\\[\\/\\2\\])?)\\s*<\\/p>/s', '$1', $pee);
259 * Checks to see if a string is utf8 encoded.
261 * NOTE: This function checks for 5-Byte sequences, UTF8
262 * has Bytes Sequences with a maximum length of 4.
264 * @author bmorel at ssi dot fr (modified)
267 * @param string $str The string to be checked
268 * @return bool True if $str fits a UTF-8 model, false otherwise.
270 function seems_utf8($str) {
271 $length = strlen($str);
272 for ($i=0; $i < $length; $i++) {
274 if ($c < 0x80) $n = 0; # 0bbbbbbb
275 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
276 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
277 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
278 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
279 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
280 else return false; # Does not match any model
281 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
282 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
290 * Converts a number of special characters into their HTML entities.
292 * Specifically deals with: &, <, >, ", and '.
294 * $quote_style can be set to ENT_COMPAT to encode " to
295 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
299 * @param string $string The text which is to be encoded.
300 * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
301 * @param string $charset Optional. The character encoding of the string. Default is false.
302 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
303 * @return string The encoded text with HTML entities.
305 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
306 $string = (string) $string;
308 if ( 0 === strlen( $string ) ) {
312 // Don't bother if there are no specialchars - saves some processing
313 if ( !preg_match( '/[&<>"\']/', $string ) ) {
317 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
318 if ( empty( $quote_style ) ) {
319 $quote_style = ENT_NOQUOTES;
320 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
321 $quote_style = ENT_QUOTES;
324 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
327 if ( !isset( $_charset ) ) {
328 $alloptions = wp_load_alloptions();
329 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
331 $charset = $_charset;
333 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
337 $_quote_style = $quote_style;
339 if ( $quote_style === 'double' ) {
340 $quote_style = ENT_COMPAT;
341 $_quote_style = ENT_COMPAT;
342 } elseif ( $quote_style === 'single' ) {
343 $quote_style = ENT_NOQUOTES;
346 // Handle double encoding ourselves
347 if ( !$double_encode ) {
348 $string = wp_specialchars_decode( $string, $_quote_style );
351 // The previous line decodes &phrase; into &phrase; We must guarantee that &phrase; is valid before proceeding.
352 $string = wp_kses_normalize_entities($string);
354 // Now proceed with custom double-encoding silliness
355 $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
358 $string = @htmlspecialchars( $string, $quote_style, $charset );
360 // Handle double encoding ourselves
361 if ( !$double_encode ) {
362 $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
365 // Backwards compatibility
366 if ( 'single' === $_quote_style ) {
367 $string = str_replace( "'", ''', $string );
374 * Converts a number of HTML entities into their special characters.
376 * Specifically deals with: &, <, >, ", and '.
378 * $quote_style can be set to ENT_COMPAT to decode " entities,
379 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
383 * @param string $string The text which is to be decoded.
384 * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
385 * @return string The decoded text without HTML entities.
387 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
388 $string = (string) $string;
390 if ( 0 === strlen( $string ) ) {
394 // Don't bother if there are no entities - saves a lot of processing
395 if ( strpos( $string, '&' ) === false ) {
399 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
400 if ( empty( $quote_style ) ) {
401 $quote_style = ENT_NOQUOTES;
402 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
403 $quote_style = ENT_QUOTES;
406 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
407 $single = array( ''' => '\'', ''' => '\'' );
408 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
409 $double = array( '"' => '"', '"' => '"', '"' => '"' );
410 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
411 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
412 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
414 if ( $quote_style === ENT_QUOTES ) {
415 $translation = array_merge( $single, $double, $others );
416 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
417 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
418 $translation = array_merge( $double, $others );
419 $translation_preg = array_merge( $double_preg, $others_preg );
420 } elseif ( $quote_style === 'single' ) {
421 $translation = array_merge( $single, $others );
422 $translation_preg = array_merge( $single_preg, $others_preg );
423 } elseif ( $quote_style === ENT_NOQUOTES ) {
424 $translation = $others;
425 $translation_preg = $others_preg;
428 // Remove zero padding on numeric entities
429 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
431 // Replace characters according to translation table
432 return strtr( $string, $translation );
436 * Checks for invalid UTF8 in a string.
440 * @param string $string The text which is to be checked.
441 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
442 * @return string The checked text.
444 function wp_check_invalid_utf8( $string, $strip = false ) {
445 $string = (string) $string;
447 if ( 0 === strlen( $string ) ) {
451 // Store the site charset as a static to avoid multiple calls to get_option()
453 if ( !isset( $is_utf8 ) ) {
454 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
460 // Check for support for utf8 in the installed PCRE library once and store the result in a static
462 if ( !isset( $utf8_pcre ) ) {
463 $utf8_pcre = @preg_match( '/^./u', 'a' );
465 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
470 // preg_match fails when it encounters invalid UTF8 in $string
471 if ( 1 === @preg_match( '/^./us', $string ) ) {
475 // Attempt to strip the bad chars if requested (not recommended)
476 if ( $strip && function_exists( 'iconv' ) ) {
477 return iconv( 'utf-8', 'utf-8', $string );
484 * Encode the Unicode values to be used in the URI.
488 * @param string $utf8_string
489 * @param int $length Max length of the string
490 * @return string String with Unicode encoded for URI.
492 function utf8_uri_encode( $utf8_string, $length = 0 ) {
498 $string_length = strlen( $utf8_string );
499 for ($i = 0; $i < $string_length; $i++ ) {
501 $value = ord( $utf8_string[ $i ] );
503 if ( $value < 128 ) {
504 if ( $length && ( $unicode_length >= $length ) )
506 $unicode .= chr($value);
509 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
513 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
515 if ( count( $values ) == $num_octets ) {
516 if ($num_octets == 3) {
517 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
518 $unicode_length += 9;
520 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
521 $unicode_length += 6;
534 * Converts all accent characters to ASCII characters.
536 * If there are no accent characters, then the string given is just returned.
540 * @param string $string Text that might have accent characters
541 * @return string Filtered string with replaced "nice" characters.
543 function remove_accents($string) {
544 if ( !preg_match('/[\x80-\xff]/', $string) )
547 if (seems_utf8($string)) {
549 // Decompositions for Latin-1 Supplement
550 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
551 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
552 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
553 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
554 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
555 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
556 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
557 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
558 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
559 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
560 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
561 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
562 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
563 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
564 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
565 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
566 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
567 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
568 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
569 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
570 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
571 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
572 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
573 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
574 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
575 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
576 chr(195).chr(182) => 'o', chr(195).chr(182) => 'o',
577 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
578 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
579 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
580 chr(195).chr(191) => 'y',
581 // Decompositions for Latin Extended-A
582 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
583 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
584 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
585 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
586 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
587 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
588 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
589 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
590 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
591 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
592 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
593 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
594 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
595 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
596 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
597 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
598 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
599 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
600 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
601 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
602 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
603 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
604 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
605 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
606 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
607 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
608 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
609 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
610 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
611 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
612 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
613 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
614 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
615 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
616 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
617 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
618 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
619 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
620 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
621 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
622 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
623 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
624 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
625 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
626 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
627 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
628 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
629 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
630 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
631 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
632 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
633 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
634 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
635 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
636 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
637 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
638 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
639 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
640 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
641 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
642 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
643 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
644 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
645 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
646 // Decompositions for Latin Extended-B
647 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
648 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
650 chr(226).chr(130).chr(172) => 'E',
652 chr(194).chr(163) => '');
654 $string = strtr($string, $chars);
656 // Assume ISO-8859-1 if not UTF-8
657 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
658 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
659 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
660 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
661 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
662 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
663 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
664 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
665 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
666 .chr(252).chr(253).chr(255);
668 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
670 $string = strtr($string, $chars['in'], $chars['out']);
671 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
672 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
673 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
680 * Sanitizes a filename replacing whitespace with dashes
682 * Removes special characters that are illegal in filenames on certain
683 * operating systems and special characters requiring special escaping
684 * to manipulate at the command line. Replaces spaces and consecutive
685 * dashes with a single dash. Trim period, dash and underscore from beginning
686 * and end of filename.
690 * @param string $filename The filename to be sanitized
691 * @return string The sanitized filename
693 function sanitize_file_name( $filename ) {
694 $filename_raw = $filename;
695 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
696 $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
697 $filename = str_replace($special_chars, '', $filename);
698 $filename = preg_replace('/[\s-]+/', '-', $filename);
699 $filename = trim($filename, '.-_');
701 // Split the filename into a base and extension[s]
702 $parts = explode('.', $filename);
704 // Return if only one extension
705 if ( count($parts) <= 2 )
706 return apply_filters('sanitize_file_name', $filename, $filename_raw);
708 // Process multiple extensions
709 $filename = array_shift($parts);
710 $extension = array_pop($parts);
711 $mimes = get_allowed_mime_types();
713 // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
714 // long alpha string not in the extension whitelist.
715 foreach ( (array) $parts as $part) {
716 $filename .= '.' . $part;
718 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
720 foreach ( $mimes as $ext_preg => $mime_match ) {
721 $ext_preg = '!(^' . $ext_preg . ')$!i';
722 if ( preg_match( $ext_preg, $part ) ) {
731 $filename .= '.' . $extension;
733 return apply_filters('sanitize_file_name', $filename, $filename_raw);
737 * Sanitize username stripping out unsafe characters.
739 * Removes tags, octets, entities, and if strict is enabled, will only keep
740 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
741 * raw username (the username in the parameter), and the value of $strict as
742 * parameters for the 'sanitize_user' filter.
745 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
746 * and $strict parameter.
748 * @param string $username The username to be sanitized.
749 * @param bool $strict If set limits $username to specific characters. Default false.
750 * @return string The sanitized username, after passing through filters.
752 function sanitize_user( $username, $strict = false ) {
753 $raw_username = $username;
754 $username = wp_strip_all_tags( $username );
755 $username = remove_accents( $username );
757 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
758 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
760 // If strict, reduce to ASCII for max portability.
762 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
764 $username = trim( $username );
765 // Consolidate contiguous whitespace
766 $username = preg_replace( '|\s+|', ' ', $username );
768 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
772 * Sanitize a string key.
774 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
778 * @param string $key String key
779 * @return string Sanitized key
781 function sanitize_key( $key ) {
783 $key = strtolower( $key );
784 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
785 return apply_filters( 'sanitize_key', $key, $raw_key );
789 * Sanitizes title or use fallback title.
791 * Specifically, HTML and PHP tags are stripped. Further actions can be added
792 * via the plugin API. If $title is empty and $fallback_title is set, the latter
797 * @param string $title The string to be sanitized.
798 * @param string $fallback_title Optional. A title to use if $title is empty.
799 * @param string $context Optional. The operation for which the string is sanitized
800 * @return string The sanitized string.
802 function sanitize_title($title, $fallback_title = '', $context = 'save') {
805 if ( 'save' == $context )
806 $title = remove_accents($title);
808 $title = apply_filters('sanitize_title', $title, $raw_title, $context);
810 if ( '' === $title || false === $title )
811 $title = $fallback_title;
816 function sanitize_title_for_query($title) {
817 return sanitize_title($title, '', 'query');
821 * Sanitizes title, replacing whitespace with dashes.
823 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
824 * Whitespace becomes a dash.
828 * @param string $title The title to be sanitized.
829 * @return string The sanitized title.
831 function sanitize_title_with_dashes($title) {
832 $title = strip_tags($title);
833 // Preserve escaped octets.
834 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
835 // Remove percent signs that are not part of an octet.
836 $title = str_replace('%', '', $title);
838 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
840 if (seems_utf8($title)) {
841 if (function_exists('mb_strtolower')) {
842 $title = mb_strtolower($title, 'UTF-8');
844 $title = utf8_uri_encode($title, 200);
847 $title = strtolower($title);
848 $title = preg_replace('/&.+?;/', '', $title); // kill entities
849 $title = str_replace('.', '-', $title);
850 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
851 $title = preg_replace('/\s+/', '-', $title);
852 $title = preg_replace('|-+|', '-', $title);
853 $title = trim($title, '-');
859 * Ensures a string is a valid SQL order by clause.
861 * Accepts one or more columns, with or without ASC/DESC, and also accepts
866 * @param string $orderby Order by string to be checked.
867 * @return string|false Returns the order by clause if it is a match, false otherwise.
869 function sanitize_sql_orderby( $orderby ){
870 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
877 * Santizes a html classname to ensure it only contains valid characters
879 * Strips the string down to A-Z,a-z,0-9,'-' if this results in an empty
880 * string then it will return the alternative value supplied.
882 * @todo Expand to support the full range of CDATA that a class attribute can contain.
886 * @param string $class The classname to be sanitized
887 * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
888 * Defaults to an empty string.
889 * @return string The sanitized value
891 function sanitize_html_class( $class, $fallback = '' ) {
892 //Strip out any % encoded octets
893 $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class);
895 //Limit to A-Z,a-z,0-9,'-'
896 $sanitized = preg_replace('/[^A-Za-z0-9-]/', '', $sanitized);
898 if ( '' == $sanitized )
899 $sanitized = $fallback;
901 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
905 * Converts a number of characters from a string.
907 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
908 * converted into correct XHTML and Unicode characters are converted to the
913 * @param string $content String of characters to be converted.
914 * @param string $deprecated Not used.
915 * @return string Converted string.
917 function convert_chars($content, $deprecated = '') {
918 if ( !empty( $deprecated ) )
919 _deprecated_argument( __FUNCTION__, '0.71' );
921 // Translation of invalid Unicode references range to valid range
922 $wp_htmltranswinuni = array(
923 '€' => '€', // the Euro sign
925 '‚' => '‚', // these are Windows CP1252 specific characters
926 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
927 '„' => '„',
928 '…' => '…',
929 '†' => '†',
930 '‡' => '‡',
931 'ˆ' => 'ˆ',
932 '‰' => '‰',
933 'Š' => 'Š',
934 '‹' => '‹',
935 'Œ' => 'Œ',
937 'Ž' => 'ž',
940 '‘' => '‘',
941 '’' => '’',
942 '“' => '“',
943 '”' => '”',
944 '•' => '•',
945 '–' => '–',
946 '—' => '—',
947 '˜' => '˜',
948 '™' => '™',
949 'š' => 'š',
950 '›' => '›',
951 'œ' => 'œ',
957 // Remove metadata tags
958 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
959 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
961 // Converts lone & characters into & (a.k.a. &)
962 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
965 $content = strtr($content, $wp_htmltranswinuni);
967 // Just a little XHTML help
968 $content = str_replace('<br>', '<br />', $content);
969 $content = str_replace('<hr>', '<hr />', $content);
975 * Will only balance the tags if forced to and the option is set to balance tags.
977 * The option 'use_balanceTags' is used for whether the tags will be balanced.
978 * Both the $force parameter and 'use_balanceTags' option will have to be true
979 * before the tags will be balanced.
983 * @param string $text Text to be balanced
984 * @param bool $force Forces balancing, ignoring the value of the option. Default false.
985 * @return string Balanced text
987 function balanceTags( $text, $force = false ) {
988 if ( !$force && get_option('use_balanceTags') == 0 )
990 return force_balance_tags( $text );
994 * Balances tags of string using a modified stack.
998 * @author Leonard Lin <leonard@acm.org>
1000 * @copyright November 4, 2001
1002 * @todo Make better - change loop condition to $text in 1.2
1003 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1004 * 1.1 Fixed handling of append/stack pop order of end text
1005 * Added Cleaning Hooks
1008 * @param string $text Text to be balanced.
1009 * @return string Balanced text.
1011 function force_balance_tags( $text ) {
1012 $tagstack = array();
1016 $single_tags = array('br', 'hr', 'img', 'input'); // Known single-entity/self-closing tags
1017 $nestable_tags = array('blockquote', 'div', 'span'); // Tags that can be immediately nested within themselves
1019 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1020 $text = str_replace('< !--', '< !--', $text);
1021 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1022 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1024 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1025 $newtext .= $tagqueue;
1027 $i = strpos($text, $regex[0]);
1028 $l = strlen($regex[0]);
1030 // clear the shifter
1033 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1034 $tag = strtolower(substr($regex[1],1));
1035 // if too many closing tags
1036 if( $stacksize <= 0 ) {
1038 // or close to be safe $tag = '/' . $tag;
1040 // if stacktop value = tag close value then pop
1041 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1042 $tag = '</' . $tag . '>'; // Close Tag
1044 array_pop( $tagstack );
1046 } else { // closing tag not at top, search for it
1047 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1048 if ( $tagstack[$j] == $tag ) {
1049 // add tag to tagqueue
1050 for ( $k = $stacksize-1; $k >= $j; $k--) {
1051 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1059 } else { // Begin Tag
1060 $tag = strtolower($regex[1]);
1064 // If self-closing or '', don't do anything.
1065 if ( substr($regex[2],-1) == '/' || $tag == '' ) {
1068 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1069 elseif ( in_array($tag, $single_tags) ) {
1071 } else { // Push the tag onto the stack
1072 // If the top of the stack is the same as the tag we want to push, close previous tag
1073 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1074 $tagqueue = '</' . array_pop ($tagstack) . '>';
1077 $stacksize = array_push ($tagstack, $tag);
1081 $attributes = $regex[2];
1082 if( !empty($attributes) )
1083 $attributes = ' '.$attributes;
1085 $tag = '<' . $tag . $attributes . '>';
1086 //If already queuing a close tag, then put this tag on, too
1087 if ( !empty($tagqueue) ) {
1092 $newtext .= substr($text, 0, $i) . $tag;
1093 $text = substr($text, $i + $l);
1097 $newtext .= $tagqueue;
1099 // Add Remaining text
1103 while( $x = array_pop($tagstack) )
1104 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1106 // WP fix for the bug with HTML comments
1107 $newtext = str_replace("< !--","<!--",$newtext);
1108 $newtext = str_replace("< !--","< !--",$newtext);
1114 * Acts on text which is about to be edited.
1116 * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
1117 * filter. If $richedit is set true htmlspecialchars(), through esc_textarea(),
1118 * will be run on the content, converting special characters to HTML entities.
1122 * @param string $content The text about to be edited.
1123 * @param bool $richedit Whether the $content should pass through htmlspecialchars(). Default false.
1124 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1126 function format_to_edit( $content, $richedit = false ) {
1127 $content = apply_filters( 'format_to_edit', $content );
1129 $content = esc_textarea( $content );
1134 * Holder for the 'format_to_post' filter.
1138 * @param string $content The text to pass through the filter.
1139 * @return string Text returned from the 'format_to_post' filter.
1141 function format_to_post($content) {
1142 $content = apply_filters('format_to_post', $content);
1147 * Add leading zeros when necessary.
1149 * If you set the threshold to '4' and the number is '10', then you will get
1150 * back '0010'. If you set the number to '4' and the number is '5000', then you
1151 * will get back '5000'.
1153 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1154 * and the size of the number. If the number is large enough, then no zeros will
1159 * @param mixed $number Number to append zeros to if not greater than threshold.
1160 * @param int $threshold Digit places number needs to be to not have zeros added.
1161 * @return string Adds leading zeros to number if needed.
1163 function zeroise($number, $threshold) {
1164 return sprintf('%0'.$threshold.'s', $number);
1168 * Adds backslashes before letters and before a number at the start of a string.
1172 * @param string $string Value to which backslashes will be added.
1173 * @return string String with backslashes inserted.
1175 function backslashit($string) {
1176 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1177 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1182 * Appends a trailing slash.
1184 * Will remove trailing slash if it exists already before adding a trailing
1185 * slash. This prevents double slashing a string or path.
1187 * The primary use of this is for paths and thus should be used for paths. It is
1188 * not restricted to paths and offers no specific path support.
1191 * @uses untrailingslashit() Unslashes string if it was slashed already.
1193 * @param string $string What to add the trailing slash to.
1194 * @return string String with trailing slash added.
1196 function trailingslashit($string) {
1197 return untrailingslashit($string) . '/';
1201 * Removes trailing slash if it exists.
1203 * The primary use of this is for paths and thus should be used for paths. It is
1204 * not restricted to paths and offers no specific path support.
1208 * @param string $string What to remove the trailing slash from.
1209 * @return string String without the trailing slash.
1211 function untrailingslashit($string) {
1212 return rtrim($string, '/');
1216 * Adds slashes to escape strings.
1218 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1219 * http://www.php.net/magic_quotes} for more details.
1223 * @param string $gpc The string returned from HTTP request data.
1224 * @return string Returns a string escaped with slashes.
1226 function addslashes_gpc($gpc) {
1227 if ( get_magic_quotes_gpc() )
1228 $gpc = stripslashes($gpc);
1230 return esc_sql($gpc);
1234 * Navigates through an array and removes slashes from the values.
1236 * If an array is passed, the array_map() function causes a callback to pass the
1237 * value back to the function. The slashes from this value will removed.
1241 * @param array|string $value The array or string to be striped.
1242 * @return array|string Stripped array (or string in the callback).
1244 function stripslashes_deep($value) {
1245 if ( is_array($value) ) {
1246 $value = array_map('stripslashes_deep', $value);
1247 } elseif ( is_object($value) ) {
1248 $vars = get_object_vars( $value );
1249 foreach ($vars as $key=>$data) {
1250 $value->{$key} = stripslashes_deep( $data );
1253 $value = stripslashes($value);
1260 * Navigates through an array and encodes the values to be used in a URL.
1262 * Uses a callback to pass the value of the array back to the function as a
1267 * @param array|string $value The array or string to be encoded.
1268 * @return array|string $value The encoded array (or string from the callback).
1270 function urlencode_deep($value) {
1271 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1276 * Converts email addresses characters to HTML entities to block spam bots.
1280 * @param string $emailaddy Email address.
1281 * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1282 * @return string Converted email address.
1284 function antispambot($emailaddy, $mailto=0) {
1285 $emailNOSPAMaddy = '';
1286 srand ((float) microtime() * 1000000);
1287 for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1288 $j = floor(rand(0, 1+$mailto));
1290 $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1292 $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1294 $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1297 $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy);
1298 return $emailNOSPAMaddy;
1302 * Callback to convert URI match to HTML A element.
1304 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1305 * make_clickable()}.
1310 * @param array $matches Single Regex Match.
1311 * @return string HTML A element with URI address.
1313 function _make_url_clickable_cb($matches) {
1317 /** Include parentheses in the URL only if paired **/
1318 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1319 $suffix = strrchr( $url, ')' ) . $suffix;
1320 $url = substr( $url, 0, strrpos( $url, ')' ) );
1323 $url = esc_url($url);
1327 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1331 * Callback to convert URL match to HTML A element.
1333 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1334 * make_clickable()}.
1339 * @param array $matches Single Regex Match.
1340 * @return string HTML A element with URL address.
1342 function _make_web_ftp_clickable_cb($matches) {
1344 $dest = $matches[2];
1345 $dest = 'http://' . $dest;
1346 $dest = esc_url($dest);
1350 // removed trailing [.,;:)] from URL
1351 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1352 $ret = substr($dest, -1);
1353 $dest = substr($dest, 0, strlen($dest)-1);
1355 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1359 * Callback to convert email address match to HTML A element.
1361 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1362 * make_clickable()}.
1367 * @param array $matches Single Regex Match.
1368 * @return string HTML A element with email address.
1370 function _make_email_clickable_cb($matches) {
1371 $email = $matches[2] . '@' . $matches[3];
1372 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1376 * Convert plaintext URI to HTML links.
1378 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1383 * @param string $ret Content to convert URIs.
1384 * @return string Content with converted URIs.
1386 function make_clickable($ret) {
1388 // in testing, using arrays here was found to be faster
1389 $ret = preg_replace_callback('#(?<!=[\'"])(?<=[*\')+.,;:!&$\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#%~/?@\[\]-]|[\'*(+.,;:!=&$](?![\b\)]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
1390 $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1391 $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1392 // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1393 $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1399 * Adds rel nofollow string to all HTML A elements in content.
1403 * @param string $text Content that may contain HTML A elements.
1404 * @return string Converted content.
1406 function wp_rel_nofollow( $text ) {
1407 // This is a pre save filter, so text is already escaped.
1408 $text = stripslashes($text);
1409 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1410 $text = esc_sql($text);
1415 * Callback to used to add rel=nofollow string to HTML A element.
1417 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1418 * string to prevent from invalidating (X)HTML.
1422 * @param array $matches Single Match
1423 * @return string HTML A Element with rel nofollow.
1425 function wp_rel_nofollow_callback( $matches ) {
1426 $text = $matches[1];
1427 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1428 return "<a $text rel=\"nofollow\">";
1432 * Convert one smiley code to the icon graphic file equivalent.
1434 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1435 * <img> string for that smiley.
1437 * @global array $wpsmiliestrans
1440 * @param string $smiley Smiley code to convert to image.
1441 * @return string Image string for smiley.
1443 function translate_smiley($smiley) {
1444 global $wpsmiliestrans;
1446 if (count($smiley) == 0) {
1450 $smiley = trim(reset($smiley));
1451 $img = $wpsmiliestrans[$smiley];
1452 $smiley_masked = esc_attr($smiley);
1454 $srcurl = apply_filters('smilies_src', includes_url("images/smilies/$img"), $img, site_url());
1456 return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1460 * Convert text equivalent of smilies to images.
1462 * Will only convert smilies if the option 'use_smilies' is true and the global
1463 * used in the function isn't empty.
1466 * @uses $wp_smiliessearch
1468 * @param string $text Content to convert smilies from text.
1469 * @return string Converted content with text smilies replaced with images.
1471 function convert_smilies($text) {
1472 global $wp_smiliessearch;
1474 if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1475 // HTML loop taken from texturize function, could possible be consolidated
1476 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1477 $stop = count($textarr);// loop stuff
1478 for ($i = 0; $i < $stop; $i++) {
1479 $content = $textarr[$i];
1480 if ((strlen($content) > 0) && ('<' != $content[0])) { // If it's not a tag
1481 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1483 $output .= $content;
1486 // return default text.
1493 * Verifies that an email is valid.
1495 * Does not grok i18n domains. Not RFC compliant.
1499 * @param string $email Email address to verify.
1500 * @param boolean $deprecated Deprecated.
1501 * @return string|bool Either false or the valid email address.
1503 function is_email( $email, $deprecated = false ) {
1504 if ( ! empty( $deprecated ) )
1505 _deprecated_argument( __FUNCTION__, '3.0' );
1507 // Test for the minimum length the email can be
1508 if ( strlen( $email ) < 3 ) {
1509 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1512 // Test for an @ character after the first position
1513 if ( strpos( $email, '@', 1 ) === false ) {
1514 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1517 // Split out the local and domain parts
1518 list( $local, $domain ) = explode( '@', $email, 2 );
1521 // Test for invalid characters
1522 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1523 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1527 // Test for sequences of periods
1528 if ( preg_match( '/\.{2,}/', $domain ) ) {
1529 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1532 // Test for leading and trailing periods and whitespace
1533 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1534 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1537 // Split the domain into subs
1538 $subs = explode( '.', $domain );
1540 // Assume the domain will have at least two subs
1541 if ( 2 > count( $subs ) ) {
1542 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1545 // Loop through each sub
1546 foreach ( $subs as $sub ) {
1547 // Test for leading and trailing hyphens and whitespace
1548 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1549 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1552 // Test for invalid characters
1553 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1554 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1558 // Congratulations your email made it!
1559 return apply_filters( 'is_email', $email, $email, null );
1563 * Convert to ASCII from email subjects.
1566 * @usedby wp_mail() handles charsets in email subjects
1568 * @param string $string Subject line
1569 * @return string Converted string to ASCII
1571 function wp_iso_descrambler($string) {
1572 /* this may only work with iso-8859-1, I'm afraid */
1573 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1576 $subject = str_replace('_', ' ', $matches[2]);
1577 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
1583 * Helper function to convert hex encoded chars to ascii
1587 * @param array $match the preg_replace_callback matches array
1589 function _wp_iso_convert( $match ) {
1590 return chr( hexdec( strtolower( $match[1] ) ) );
1594 * Returns a date in the GMT equivalent.
1596 * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1597 * value of the 'gmt_offset' option. Return format can be overridden using the
1598 * $format parameter. If PHP5 is supported, the function uses the DateTime and
1599 * DateTimeZone objects to respect time zone differences in DST.
1603 * @uses get_option() to retrieve the the value of 'gmt_offset'.
1604 * @param string $string The date to be converted.
1605 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1606 * @return string GMT version of the date provided.
1608 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1609 preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches);
1610 $tz = get_option('timezone_string');
1611 if( class_exists('DateTime') && $tz ) {
1613 date_default_timezone_set( $tz );
1614 $datetime = new DateTime( $string );
1615 $datetime->setTimezone( new DateTimeZone('UTC') );
1616 $offset = $datetime->getOffset();
1617 $datetime->modify( '+' . $offset / 3600 . ' hours');
1618 $string_gmt = gmdate($format, $datetime->format('U'));
1620 date_default_timezone_set('UTC');
1624 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1625 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1631 * Converts a GMT date into the correct format for the blog.
1633 * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1634 * gmt_offset.Return format can be overridden using the $format parameter
1638 * @param string $string The date to be converted.
1639 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1640 * @return string Formatted date relative to the GMT offset.
1642 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1643 preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches);
1644 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1645 $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1646 return $string_localtime;
1650 * Computes an offset in seconds from an iso8601 timezone.
1654 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1655 * @return int|float The offset in seconds.
1657 function iso8601_timezone_to_offset($timezone) {
1658 // $timezone is either 'Z' or '[+|-]hhmm'
1659 if ($timezone == 'Z') {
1662 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1663 $hours = intval(substr($timezone, 1, 2));
1664 $minutes = intval(substr($timezone, 3, 4)) / 60;
1665 $offset = $sign * 3600 * ($hours + $minutes);
1671 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1675 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1676 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1677 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1679 function iso8601_to_datetime($date_string, $timezone = 'user') {
1680 $timezone = strtolower($timezone);
1682 if ($timezone == 'gmt') {
1684 preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits);
1686 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1687 $offset = iso8601_timezone_to_offset($date_bits[7]);
1688 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1689 $offset = 3600 * get_option('gmt_offset');
1692 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1693 $timestamp -= $offset;
1695 return gmdate('Y-m-d H:i:s', $timestamp);
1697 } else if ($timezone == 'user') {
1698 return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string);
1703 * Adds a element attributes to open links in new windows.
1705 * Comment text in popup windows should be filtered through this. Right now it's
1706 * a moderately dumb function, ideally it would detect whether a target or rel
1707 * attribute was already there and adjust its actions accordingly.
1711 * @param string $text Content to replace links to open in a new window.
1712 * @return string Content that has filtered links.
1714 function popuplinks($text) {
1715 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1720 * Strips out all characters that are not allowable in an email.
1724 * @param string $email Email address to filter.
1725 * @return string Filtered email address.
1727 function sanitize_email( $email ) {
1728 // Test for the minimum length the email can be
1729 if ( strlen( $email ) < 3 ) {
1730 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1733 // Test for an @ character after the first position
1734 if ( strpos( $email, '@', 1 ) === false ) {
1735 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1738 // Split out the local and domain parts
1739 list( $local, $domain ) = explode( '@', $email, 2 );
1742 // Test for invalid characters
1743 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1744 if ( '' === $local ) {
1745 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1749 // Test for sequences of periods
1750 $domain = preg_replace( '/\.{2,}/', '', $domain );
1751 if ( '' === $domain ) {
1752 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1755 // Test for leading and trailing periods and whitespace
1756 $domain = trim( $domain, " \t\n\r\0\x0B." );
1757 if ( '' === $domain ) {
1758 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1761 // Split the domain into subs
1762 $subs = explode( '.', $domain );
1764 // Assume the domain will have at least two subs
1765 if ( 2 > count( $subs ) ) {
1766 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1769 // Create an array that will contain valid subs
1770 $new_subs = array();
1772 // Loop through each sub
1773 foreach ( $subs as $sub ) {
1774 // Test for leading and trailing hyphens
1775 $sub = trim( $sub, " \t\n\r\0\x0B-" );
1777 // Test for invalid characters
1778 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
1780 // If there's anything left, add it to the valid subs
1781 if ( '' !== $sub ) {
1786 // If there aren't 2 or more valid subs
1787 if ( 2 > count( $new_subs ) ) {
1788 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1791 // Join valid subs into the new domain
1792 $domain = join( '.', $new_subs );
1794 // Put the email back together
1795 $email = $local . '@' . $domain;
1797 // Congratulations your email made it!
1798 return apply_filters( 'sanitize_email', $email, $email, null );
1802 * Determines the difference between two timestamps.
1804 * The difference is returned in a human readable format such as "1 hour",
1805 * "5 mins", "2 days".
1809 * @param int $from Unix timestamp from which the difference begins.
1810 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1811 * @return string Human readable time difference.
1813 function human_time_diff( $from, $to = '' ) {
1816 $diff = (int) abs($to - $from);
1817 if ($diff <= 3600) {
1818 $mins = round($diff / 60);
1822 /* translators: min=minute */
1823 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1824 } else if (($diff <= 86400) && ($diff > 3600)) {
1825 $hours = round($diff / 3600);
1829 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1830 } elseif ($diff >= 86400) {
1831 $days = round($diff / 86400);
1835 $since = sprintf(_n('%s day', '%s days', $days), $days);
1841 * Generates an excerpt from the content, if needed.
1843 * The excerpt word amount will be 55 words and if the amount is greater than
1844 * that, then the string ' [...]' will be appended to the excerpt. If the string
1845 * is less than 55 words, then the content will be returned as is.
1847 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
1848 * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
1852 * @param string $text The excerpt. If set to empty an excerpt is generated.
1853 * @return string The excerpt.
1855 function wp_trim_excerpt($text) {
1856 $raw_excerpt = $text;
1857 if ( '' == $text ) {
1858 $text = get_the_content('');
1860 $text = strip_shortcodes( $text );
1862 $text = apply_filters('the_content', $text);
1863 $text = str_replace(']]>', ']]>', $text);
1864 $text = strip_tags($text);
1865 $excerpt_length = apply_filters('excerpt_length', 55);
1866 $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
1867 $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
1868 if ( count($words) > $excerpt_length ) {
1870 $text = implode(' ', $words);
1871 $text = $text . $excerpt_more;
1873 $text = implode(' ', $words);
1876 return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1880 * Converts named entities into numbered entities.
1884 * @param string $text The text within which entities will be converted.
1885 * @return string Text with converted entities.
1887 function ent2ncr($text) {
1889 '"' => '"',
1891 '⁄' => '/',
1895 ' ' => ' ',
1896 '¡' => '¡',
1897 '¢' => '¢',
1898 '£' => '£',
1899 '¤' => '¤',
1900 '¥' => '¥',
1901 '¦' => '¦',
1902 '&brkbar;' => '¦',
1903 '§' => '§',
1904 '¨' => '¨',
1905 '¨' => '¨',
1906 '©' => '©',
1907 'ª' => 'ª',
1908 '«' => '«',
1909 '¬' => '¬',
1910 '­' => '­',
1911 '®' => '®',
1912 '¯' => '¯',
1913 '&hibar;' => '¯',
1914 '°' => '°',
1915 '±' => '±',
1916 '²' => '²',
1917 '³' => '³',
1918 '´' => '´',
1919 'µ' => 'µ',
1920 '¶' => '¶',
1921 '·' => '·',
1922 '¸' => '¸',
1923 '¹' => '¹',
1924 'º' => 'º',
1925 '»' => '»',
1926 '¼' => '¼',
1927 '½' => '½',
1928 '¾' => '¾',
1929 '¿' => '¿',
1930 'À' => 'À',
1931 'Á' => 'Á',
1932 'Â' => 'Â',
1933 'Ã' => 'Ã',
1934 'Ä' => 'Ä',
1935 'Å' => 'Å',
1936 'Æ' => 'Æ',
1937 'Ç' => 'Ç',
1938 'È' => 'È',
1939 'É' => 'É',
1940 'Ê' => 'Ê',
1941 'Ë' => 'Ë',
1942 'Ì' => 'Ì',
1943 'Í' => 'Í',
1944 'Î' => 'Î',
1945 'Ï' => 'Ï',
1946 'Ð' => 'Ð',
1947 'Ñ' => 'Ñ',
1948 'Ò' => 'Ò',
1949 'Ó' => 'Ó',
1950 'Ô' => 'Ô',
1951 'Õ' => 'Õ',
1952 'Ö' => 'Ö',
1953 '×' => '×',
1954 'Ø' => 'Ø',
1955 'Ù' => 'Ù',
1956 'Ú' => 'Ú',
1957 'Û' => 'Û',
1958 'Ü' => 'Ü',
1959 'Ý' => 'Ý',
1960 'Þ' => 'Þ',
1961 'ß' => 'ß',
1962 'à' => 'à',
1963 'á' => 'á',
1964 'â' => 'â',
1965 'ã' => 'ã',
1966 'ä' => 'ä',
1967 'å' => 'å',
1968 'æ' => 'æ',
1969 'ç' => 'ç',
1970 'è' => 'è',
1971 'é' => 'é',
1972 'ê' => 'ê',
1973 'ë' => 'ë',
1974 'ì' => 'ì',
1975 'í' => 'í',
1976 'î' => 'î',
1977 'ï' => 'ï',
1978 'ð' => 'ð',
1979 'ñ' => 'ñ',
1980 'ò' => 'ò',
1981 'ó' => 'ó',
1982 'ô' => 'ô',
1983 'õ' => 'õ',
1984 'ö' => 'ö',
1985 '÷' => '÷',
1986 'ø' => 'ø',
1987 'ù' => 'ù',
1988 'ú' => 'ú',
1989 'û' => 'û',
1990 'ü' => 'ü',
1991 'ý' => 'ý',
1992 'þ' => 'þ',
1993 'ÿ' => 'ÿ',
1994 'Œ' => 'Œ',
1995 'œ' => 'œ',
1996 'Š' => 'Š',
1997 'š' => 'š',
1998 'Ÿ' => 'Ÿ',
1999 'ƒ' => 'ƒ',
2000 'ˆ' => 'ˆ',
2001 '˜' => '˜',
2002 'Α' => 'Α',
2003 'Β' => 'Β',
2004 'Γ' => 'Γ',
2005 'Δ' => 'Δ',
2006 'Ε' => 'Ε',
2007 'Ζ' => 'Ζ',
2008 'Η' => 'Η',
2009 'Θ' => 'Θ',
2010 'Ι' => 'Ι',
2011 'Κ' => 'Κ',
2012 'Λ' => 'Λ',
2016 'Ο' => 'Ο',
2018 'Ρ' => 'Ρ',
2019 'Σ' => 'Σ',
2020 'Τ' => 'Τ',
2021 'Υ' => 'Υ',
2022 'Φ' => 'Φ',
2023 'Χ' => 'Χ',
2024 'Ψ' => 'Ψ',
2025 'Ω' => 'Ω',
2026 'α' => 'α',
2027 'β' => 'β',
2028 'γ' => 'γ',
2029 'δ' => 'δ',
2030 'ε' => 'ε',
2031 'ζ' => 'ζ',
2032 'η' => 'η',
2033 'θ' => 'θ',
2034 'ι' => 'ι',
2035 'κ' => 'κ',
2036 'λ' => 'λ',
2040 'ο' => 'ο',
2042 'ρ' => 'ρ',
2043 'ς' => 'ς',
2044 'σ' => 'σ',
2045 'τ' => 'τ',
2046 'υ' => 'υ',
2047 'φ' => 'φ',
2048 'χ' => 'χ',
2049 'ψ' => 'ψ',
2050 'ω' => 'ω',
2051 'ϑ' => 'ϑ',
2052 'ϒ' => 'ϒ',
2053 'ϖ' => 'ϖ',
2054 ' ' => ' ',
2055 ' ' => ' ',
2056 ' ' => ' ',
2057 '‌' => '‌',
2058 '‍' => '‍',
2059 '‎' => '‎',
2060 '‏' => '‏',
2061 '–' => '–',
2062 '—' => '—',
2063 '‘' => '‘',
2064 '’' => '’',
2065 '‚' => '‚',
2066 '“' => '“',
2067 '”' => '”',
2068 '„' => '„',
2069 '†' => '†',
2070 '‡' => '‡',
2071 '•' => '•',
2072 '…' => '…',
2073 '‰' => '‰',
2074 '′' => '′',
2075 '″' => '″',
2076 '‹' => '‹',
2077 '›' => '›',
2078 '‾' => '‾',
2079 '⁄' => '⁄',
2080 '€' => '€',
2081 'ℑ' => 'ℑ',
2082 '℘' => '℘',
2083 'ℜ' => 'ℜ',
2084 '™' => '™',
2085 'ℵ' => 'ℵ',
2086 '↵' => '↵',
2087 '⇐' => '⇐',
2088 '⇑' => '⇑',
2089 '⇒' => '⇒',
2090 '⇓' => '⇓',
2091 '⇔' => '⇔',
2092 '∀' => '∀',
2093 '∂' => '∂',
2094 '∃' => '∃',
2095 '∅' => '∅',
2096 '∇' => '∇',
2097 '∈' => '∈',
2098 '∉' => '∉',
2099 '∋' => '∋',
2100 '∏' => '∏',
2101 '∑' => '∑',
2102 '−' => '−',
2103 '∗' => '∗',
2104 '√' => '√',
2105 '∝' => '∝',
2106 '∞' => '∞',
2107 '∠' => '∠',
2108 '∧' => '∧',
2109 '∨' => '∨',
2110 '∩' => '∩',
2111 '∪' => '∪',
2112 '∫' => '∫',
2113 '∴' => '∴',
2114 '∼' => '∼',
2115 '≅' => '≅',
2116 '≈' => '≈',
2117 '≠' => '≠',
2118 '≡' => '≡',
2119 '≤' => '≤',
2120 '≥' => '≥',
2121 '⊂' => '⊂',
2122 '⊃' => '⊃',
2123 '⊄' => '⊄',
2124 '⊆' => '⊆',
2125 '⊇' => '⊇',
2126 '⊕' => '⊕',
2127 '⊗' => '⊗',
2128 '⊥' => '⊥',
2129 '⋅' => '⋅',
2130 '⌈' => '⌈',
2131 '⌉' => '⌉',
2132 '⌊' => '⌊',
2133 '⌋' => '⌋',
2134 '⟨' => '〈',
2135 '⟩' => '〉',
2136 '←' => '←',
2137 '↑' => '↑',
2138 '→' => '→',
2139 '↓' => '↓',
2140 '↔' => '↔',
2141 '◊' => '◊',
2142 '♠' => '♠',
2143 '♣' => '♣',
2144 '♥' => '♥',
2145 '♦' => '♦'
2148 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2152 * Formats text for the rich text editor.
2154 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2155 * be applied to an empty string.
2159 * @param string $text The text to be formatted.
2160 * @return string The formatted text after filter is applied.
2162 function wp_richedit_pre($text) {
2163 // Filtering a blank results in an annoying <br />\n
2164 if ( empty($text) ) return apply_filters('richedit_pre', '');
2166 $output = convert_chars($text);
2167 $output = wpautop($output);
2168 $output = htmlspecialchars($output, ENT_NOQUOTES);
2170 return apply_filters('richedit_pre', $output);
2174 * Formats text for the HTML editor.
2176 * Unless $output is empty it will pass through htmlspecialchars before the
2177 * 'htmledit_pre' filter is applied.
2181 * @param string $output The text to be formatted.
2182 * @return string Formatted text after filter applied.
2184 function wp_htmledit_pre($output) {
2185 if ( !empty($output) )
2186 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2188 return apply_filters('htmledit_pre', $output);
2192 * Perform a deep string replace operation to ensure the values in $search are no longer present
2194 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2195 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2196 * str_replace would return
2201 * @param string|array $search
2202 * @param string $subject
2203 * @return string The processed string
2205 function _deep_replace( $search, $subject ) {
2207 $subject = (string) $subject;
2210 foreach ( (array) $search as $val ) {
2211 while ( strpos( $subject, $val ) !== false ) {
2213 $subject = str_replace( $val, '', $subject );
2222 * Escapes data for use in a MySQL query
2224 * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2227 * @param string $sql Unescaped SQL data
2228 * @return string The cleaned $sql
2230 function esc_sql( $sql ) {
2232 return $wpdb->escape( $sql );
2236 * Checks and cleans a URL.
2238 * A number of characters are removed from the URL. If the URL is for displaying
2239 * (the default behaviour) amperstands are also replaced. The 'clean_url' filter
2240 * is applied to the returned cleaned URL.
2243 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2244 * via $protocols or the common ones set in the function.
2246 * @param string $url The URL to be cleaned.
2247 * @param array $protocols Optional. An array of acceptable protocols.
2248 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2249 * @param string $_context Private. Use esc_url_raw() for database usage.
2250 * @return string The cleaned $url after the 'clean_url' filter is applied.
2252 function esc_url( $url, $protocols = null, $_context = 'display' ) {
2253 $original_url = $url;
2257 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2258 $strip = array('%0d', '%0a', '%0D', '%0A');
2259 $url = _deep_replace($strip, $url);
2260 $url = str_replace(';//', '://', $url);
2261 /* If the URL doesn't appear to contain a scheme, we
2262 * presume it needs http:// appended (unless a relative
2263 * link starting with / or a php file).
2265 if ( strpos($url, ':') === false &&
2266 substr( $url, 0, 1 ) != '/' && substr( $url, 0, 1 ) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2267 $url = 'http://' . $url;
2269 // Replace ampersands and single quotes only when displaying.
2270 if ( 'display' == $_context ) {
2271 $url = wp_kses_normalize_entities( $url );
2272 $url = str_replace( '&', '&', $url );
2273 $url = str_replace( "'", ''', $url );
2276 if ( !is_array($protocols) )
2277 $protocols = array ('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn');
2278 if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2281 return apply_filters('clean_url', $url, $original_url, $_context);
2285 * Performs esc_url() for database usage.
2290 * @param string $url The URL to be cleaned.
2291 * @param array $protocols An array of acceptable protocols.
2292 * @return string The cleaned URL.
2294 function esc_url_raw( $url, $protocols = null ) {
2295 return esc_url( $url, $protocols, 'db' );
2299 * Convert entities, while preserving already-encoded entities.
2301 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2305 * @param string $myHTML The text to be converted.
2306 * @return string Converted text.
2308 function htmlentities2($myHTML) {
2309 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2310 $translation_table[chr(38)] = '&';
2311 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
2315 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2317 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
2318 * (in a tag attribute, for example onclick="..."). Note that the strings have to
2319 * be in single quotes. The filter 'js_escape' is also applied here.
2323 * @param string $text The text to be escaped.
2324 * @return string Escaped text.
2326 function esc_js( $text ) {
2327 $safe_text = wp_check_invalid_utf8( $text );
2328 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2329 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2330 $safe_text = str_replace( "\r", '', $safe_text );
2331 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2332 return apply_filters( 'js_escape', $safe_text, $text );
2336 * Escaping for HTML blocks.
2340 * @param string $text
2343 function esc_html( $text ) {
2344 $safe_text = wp_check_invalid_utf8( $text );
2345 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2346 return apply_filters( 'esc_html', $safe_text, $text );
2350 * Escaping for HTML attributes.
2354 * @param string $text
2357 function esc_attr( $text ) {
2358 $safe_text = wp_check_invalid_utf8( $text );
2359 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2360 return apply_filters( 'attribute_escape', $safe_text, $text );
2364 * Escaping for textarea values.
2368 * @param string $text
2371 function esc_textarea( $text ) {
2372 $safe_text = htmlspecialchars( $text, ENT_QUOTES );
2373 return apply_filters( 'esc_textarea', $safe_text, $text );
2377 * Escape a HTML tag name.
2381 * @param string $tag_name
2384 function tag_escape($tag_name) {
2385 $safe_tag = strtolower( preg_replace('/[^a-zA-Z_:]/', '', $tag_name) );
2386 return apply_filters('tag_escape', $safe_tag, $tag_name);
2390 * Escapes text for SQL LIKE special characters % and _.
2394 * @param string $text The text to be escaped.
2395 * @return string text, safe for inclusion in LIKE query.
2397 function like_escape($text) {
2398 return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2402 * Convert full URL paths to absolute paths.
2404 * Removes the http or https protocols and the domain. Keeps the path '/' at the
2405 * beginning, so it isn't a true relative link, but from the web root base.
2409 * @param string $link Full URL path.
2410 * @return string Absolute path.
2412 function wp_make_link_relative( $link ) {
2413 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2417 * Sanitises various option values based on the nature of the option.
2419 * This is basically a switch statement which will pass $value through a number
2420 * of functions depending on the $option.
2424 * @param string $option The name of the option.
2425 * @param string $value The unsanitised value.
2426 * @return string Sanitized value.
2428 function sanitize_option($option, $value) {
2430 switch ( $option ) {
2432 $value = sanitize_email($value);
2433 if ( !is_email($value) ) {
2434 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2435 if ( function_exists('add_settings_error') )
2436 add_settings_error('admin_email', 'invalid_admin_email', __('The email address entered did not appear to be a valid email address. Please enter a valid email address.'));
2440 case 'thumbnail_size_w':
2441 case 'thumbnail_size_h':
2442 case 'medium_size_w':
2443 case 'medium_size_h':
2444 case 'large_size_w':
2445 case 'large_size_h':
2446 case 'embed_size_h':
2447 case 'default_post_edit_rows':
2448 case 'mailserver_port':
2449 case 'comment_max_links':
2450 case 'page_on_front':
2451 case 'page_for_posts':
2452 case 'rss_excerpt_length':
2453 case 'default_category':
2454 case 'default_email_category':
2455 case 'default_link_category':
2456 case 'close_comments_days_old':
2457 case 'comments_per_page':
2458 case 'thread_comments_depth':
2459 case 'users_can_register':
2460 case 'start_of_week':
2461 $value = absint( $value );
2464 case 'embed_size_w':
2465 if ( '' !== $value )
2466 $value = absint( $value );
2469 case 'posts_per_page':
2470 case 'posts_per_rss':
2471 $value = (int) $value;
2472 if ( empty($value) )
2475 $value = abs($value);
2478 case 'default_ping_status':
2479 case 'default_comment_status':
2480 // Options that if not there have 0 value but need to be something like "closed"
2481 if ( $value == '0' || $value == '')
2485 case 'blogdescription':
2487 $value = addslashes($value);
2488 $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2489 $value = stripslashes($value);
2490 $value = esc_html( $value );
2493 case 'blog_charset':
2494 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2499 case 'mailserver_url':
2500 case 'mailserver_login':
2501 case 'mailserver_pass':
2504 $value = strip_tags($value);
2505 $value = addslashes($value);
2506 $value = wp_filter_kses($value); // calls stripslashes then addslashes
2507 $value = stripslashes($value);
2511 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2515 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2516 $value = esc_url_raw($value);
2518 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2519 if ( function_exists('add_settings_error') )
2520 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2525 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2526 $value = esc_url_raw($value);
2528 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2529 if ( function_exists('add_settings_error') )
2530 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2535 $value = apply_filters("sanitize_option_{$option}", $value, $option);
2543 * Parses a string into variables to be stored in an array.
2545 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2546 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2549 * @uses apply_filters() for the 'wp_parse_str' filter.
2551 * @param string $string The string to be parsed.
2552 * @param array $array Variables will be stored in this array.
2554 function wp_parse_str( $string, &$array ) {
2555 parse_str( $string, $array );
2556 if ( get_magic_quotes_gpc() )
2557 $array = stripslashes_deep( $array );
2558 $array = apply_filters( 'wp_parse_str', $array );
2562 * Convert lone less than signs.
2564 * KSES already converts lone greater than signs.
2566 * @uses wp_pre_kses_less_than_callback in the callback function.
2569 * @param string $text Text to be converted.
2570 * @return string Converted text.
2572 function wp_pre_kses_less_than( $text ) {
2573 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2577 * Callback function used by preg_replace.
2579 * @uses esc_html to format the $matches text.
2582 * @param array $matches Populated by matches to preg_replace.
2583 * @return string The text returned after esc_html if needed.
2585 function wp_pre_kses_less_than_callback( $matches ) {
2586 if ( false === strpos($matches[0], '>') )
2587 return esc_html($matches[0]);
2592 * WordPress implementation of PHP sprintf() with filters.
2595 * @link http://www.php.net/sprintf
2597 * @param string $pattern The string which formatted args are inserted.
2598 * @param mixed $args,... Arguments to be formatted into the $pattern string.
2599 * @return string The formatted string.
2601 function wp_sprintf( $pattern ) {
2602 $args = func_get_args( );
2603 $len = strlen($pattern);
2607 while ( $len > $start ) {
2608 // Last character: append and break
2609 if ( strlen($pattern) - 1 == $start ) {
2610 $result .= substr($pattern, -1);
2614 // Literal %: append and continue
2615 if ( substr($pattern, $start, 2) == '%%' ) {
2621 // Get fragment before next %
2622 $end = strpos($pattern, '%', $start + 1);
2623 if ( false === $end )
2625 $fragment = substr($pattern, $start, $end - $start);
2627 // Fragment has a specifier
2628 if ( $pattern[$start] == '%' ) {
2629 // Find numbered arguments or take the next one in order
2630 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2631 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2632 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2635 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2638 // Apply filters OR sprintf
2639 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2640 if ( $_fragment != $fragment )
2641 $fragment = $_fragment;
2643 $fragment = sprintf($fragment, strval($arg) );
2646 // Append to result and move to next fragment
2647 $result .= $fragment;
2654 * Localize list items before the rest of the content.
2656 * The '%l' must be at the first characters can then contain the rest of the
2657 * content. The list items will have ', ', ', and', and ' and ' added depending
2658 * on the amount of list items in the $args parameter.
2662 * @param string $pattern Content containing '%l' at the beginning.
2663 * @param array $args List items to prepend to the content and replace '%l'.
2664 * @return string Localized list items and rest of the content.
2666 function wp_sprintf_l($pattern, $args) {
2668 if ( substr($pattern, 0, 2) != '%l' )
2671 // Nothing to work with
2675 // Translate and filter the delimiter set (avoid ampersands and entities here)
2676 $l = apply_filters('wp_sprintf_l', array(
2677 /* translators: used between list items, there is a space after the coma */
2678 'between' => __(', '),
2679 /* translators: used between list items, there is a space after the and */
2680 'between_last_two' => __(', and '),
2681 /* translators: used between only two list items, there is a space after the and */
2682 'between_only_two' => __(' and '),
2685 $args = (array) $args;
2686 $result = array_shift($args);
2687 if ( count($args) == 1 )
2688 $result .= $l['between_only_two'] . array_shift($args);
2689 // Loop when more than two args
2692 $arg = array_shift($args);
2695 $result .= $l['between_last_two'] . $arg;
2697 $result .= $l['between'] . $arg;
2699 return $result . substr($pattern, 2);
2703 * Safely extracts not more than the first $count characters from html string.
2705 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2706 * be counted as one character. For example & will be counted as 4, < as
2711 * @param integer $str String to get the excerpt from.
2712 * @param integer $count Maximum number of characters to take.
2713 * @return string The excerpt.
2715 function wp_html_excerpt( $str, $count ) {
2716 $str = wp_strip_all_tags( $str, true );
2717 $str = mb_substr( $str, 0, $count );
2718 // remove part of an entity at the end
2719 $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2724 * Add a Base url to relative links in passed content.
2726 * By default it supports the 'src' and 'href' attributes. However this can be
2727 * changed via the 3rd param.
2731 * @param string $content String to search for links in.
2732 * @param string $base The base URL to prefix to links.
2733 * @param array $attrs The attributes which should be processed.
2734 * @return string The processed content.
2736 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2737 global $_links_add_base;
2738 $_links_add_base = $base;
2739 $attrs = implode('|', (array)$attrs);
2740 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
2744 * Callback to add a base url to relative links in passed content.
2749 * @param string $m The matched link.
2750 * @return string The processed link.
2752 function _links_add_base($m) {
2753 global $_links_add_base;
2754 //1 = attribute name 2 = quotation mark 3 = URL
2755 return $m[1] . '=' . $m[2] .
2756 (strpos($m[3], 'http://') === false ?
2757 path_join($_links_add_base, $m[3]) :
2763 * Adds a Target attribute to all links in passed content.
2765 * This function by default only applies to <a> tags, however this can be
2766 * modified by the 3rd param.
2768 * <b>NOTE:</b> Any current target attributed will be striped and replaced.
2772 * @param string $content String to search for links in.
2773 * @param string $target The Target to add to the links.
2774 * @param array $tags An array of tags to apply to.
2775 * @return string The processed content.
2777 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2778 global $_links_add_target;
2779 $_links_add_target = $target;
2780 $tags = implode('|', (array)$tags);
2781 return preg_replace_callback( "!<($tags)(.+?)>!i", '_links_add_target', $content );
2785 * Callback to add a target attribute to all links in passed content.
2790 * @param string $m The matched link.
2791 * @return string The processed link.
2793 function _links_add_target( $m ) {
2794 global $_links_add_target;
2796 $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2797 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
2800 // normalize EOL characters and strip duplicate whitespace
2801 function normalize_whitespace( $str ) {
2803 $str = str_replace("\r", "\n", $str);
2804 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
2809 * Properly strip all HTML tags including script and style
2813 * @param string $string String containing HTML tags
2814 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
2815 * @return string The processed string.
2817 function wp_strip_all_tags($string, $remove_breaks = false) {
2818 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
2819 $string = strip_tags($string);
2821 if ( $remove_breaks )
2822 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
2824 return trim($string);
2828 * Sanitize a string from user input or from the db
2830 * check for invalid UTF-8,
2831 * Convert single < characters to entity,
2833 * remove line breaks, tabs and extra white space,
2838 * @param string $str
2841 function sanitize_text_field($str) {
2842 $filtered = wp_check_invalid_utf8( $str );
2844 if ( strpos($filtered, '<') !== false ) {
2845 $filtered = wp_pre_kses_less_than( $filtered );
2846 // This will strip extra whitespace for us.
2847 $filtered = wp_strip_all_tags( $filtered, true );
2849 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
2854 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
2855 $filtered = str_replace($match[0], '', $filtered);
2860 // Strip out the whitespace that may now exist after removing the octets.
2861 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
2864 return apply_filters('sanitize_text_field', $filtered, $str);
2868 * i18n friendly version of basename()
2872 * @param string $path A path.
2873 * @param string $suffix If the filename ends in suffix this will also be cut off.
2876 function wp_basename( $path, $suffix = '' ) {
2877 return urldecode( basename( str_replace( '%2F', '/', urlencode( $path ) ), $suffix ) );
2881 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
2883 * Violating our coding standards for a good function name.
2887 function capital_P_dangit( $text ) {
2888 // Simple replacement for titles
2889 if ( 'the_title' === current_filter() )
2890 return str_replace( 'Wordpress', 'WordPress', $text );
2891 // Still here? Use the more judicious replacement
2892 static $dblq = false;
2893 if ( false === $dblq )
2894 $dblq = _x('“', 'opening curly quote');
2896 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
2897 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),