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 $opening_quote, $closing_quote, $en_dash, $em_dash, $default_no_texturize_tags, $default_no_texturize_shortcodes, $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements;
33 // No need to set up these static variables more than once
34 if ( empty( $opening_quote ) ) {
35 /* translators: opening curly quote */
36 $opening_quote = _x('“', 'opening curly quote');
37 /* translators: closing curly quote */
38 $closing_quote = _x('”', 'closing curly quote');
39 /* translators: en dash */
40 $en_dash = _x('–', 'en dash');
41 /* translators: em dash */
42 $em_dash = _x('—', 'em dash');
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($em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', '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');
63 // Transform into regexp sub-expression used in _wptexturize_pushpop_element
64 // Must do this everytime in case plugins use these filters in a context sensitive manner
65 $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
66 $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
68 $no_texturize_tags_stack = array();
69 $no_texturize_shortcodes_stack = array();
71 $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
73 foreach ( $textarr as &$curl ) {
77 // Only call _wptexturize_pushpop_element if first char is correct tag opening
79 if ( '<' === $first ) {
80 _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
81 } elseif ( '[' === $first ) {
82 _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
83 } elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
84 // This is not a tag, nor is the texturization disabled static strings
85 $curl = str_replace($static_characters, $static_replacements, $curl);
86 // regular expressions
87 $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
89 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
91 return implode( '', $textarr );
95 * Search for disabled element tags. Push element to stack on tag open and pop
96 * on tag close. Assumes first character of $text is tag opening.
101 * @param string $text Text to check. First character is assumed to be $opening
102 * @param array $stack Array used as stack of opened tag elements
103 * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
104 * @param string $opening Tag opening character, assumed to be 1 character long
105 * @param string $opening Tag closing character
108 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
109 // Check if it is a closing tag -- otherwise assume opening tag
110 if (strncmp($opening . '/', $text, 2)) {
111 // Opening? Check $text+1 against disabled elements
112 if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
114 * This disables texturize until we find a closing tag of our type
115 * (e.g. <pre>) even if there was invalid nesting before that
117 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
118 * "baba" won't be texturize
121 array_push($stack, $matches[1]);
124 // Closing? Check $text+2 against disabled elements
125 $c = preg_quote($closing, '/');
126 if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
127 $last = array_pop($stack);
129 // Make sure it matches the opening tag
130 if ($last != $matches[1])
131 array_push($stack, $last);
137 * Accepts matches array from preg_replace_callback in wpautop() or a string.
139 * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
140 * converted into paragraphs or line-breaks.
144 * @param array|string $matches The array or string
145 * @return string The pre block without paragraph/line-break conversion.
147 function clean_pre($matches) {
148 if ( is_array($matches) )
149 $text = $matches[1] . $matches[2] . "</pre>";
153 $text = str_replace('<br />', '', $text);
154 $text = str_replace('<p>', "\n", $text);
155 $text = str_replace('</p>', '', $text);
161 * Replaces double line-breaks with paragraph elements.
163 * A group of regex replaces used to identify text formatted with newlines and
164 * replace double line-breaks with HTML paragraph tags. The remaining
165 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
170 * @param string $pee The text which has to be formatted.
171 * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
172 * @return string Text which has been converted into correct paragraph tags.
174 function wpautop($pee, $br = 1) {
176 if ( trim($pee) === '' )
178 $pee = $pee . "\n"; // just to make things a little easier, pad the end
179 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
180 // Space things out a little
181 $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)';
182 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
183 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
184 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
185 if ( strpos($pee, '<object') !== false ) {
186 $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
187 $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
189 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
190 // make paragraphs, including one at the end
191 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
193 foreach ( $pees as $tinkle )
194 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
195 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
196 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
197 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
198 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
199 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
200 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
201 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
202 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
204 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
205 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
206 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
208 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
209 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
210 if (strpos($pee, '<pre') !== false)
211 $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
212 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
218 * Newline preservation help function for wpautop
222 * @param array $matches preg_replace_callback matches array
225 function _autop_newline_preservation_helper( $matches ) {
226 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
230 * Don't auto-p wrap shortcodes that stand alone
232 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
236 * @param string $pee The content.
237 * @return string The filtered content.
239 function shortcode_unautop( $pee ) {
240 global $shortcode_tags;
242 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
246 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
250 . '<p>' // Opening paragraph
251 . '\\s*+' // Optional leading whitespace
252 . '(' // 1: The shortcode
253 . '\\[' // Opening bracket
254 . "($tagregexp)" // 2: Shortcode name
255 . '\\b' // Word boundary
256 // Unroll the loop: Inside the opening shortcode tag
257 . '[^\\]\\/]*' // Not a closing bracket or forward slash
259 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
260 . '[^\\]\\/]*' // Not a closing bracket or forward slash
263 . '\\/\\]' // Self closing tag and closing bracket
265 . '\\]' // Closing bracket
266 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
267 . '[^\\[]*+' // Not an opening bracket
269 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
270 . '[^\\[]*+' // Not an opening bracket
272 . '\\[\\/\\2\\]' // Closing shortcode tag
276 . '\\s*+' // optional trailing whitespace
277 . '<\\/p>' // closing paragraph
280 return preg_replace( $pattern, '$1', $pee );
284 * Checks to see if a string is utf8 encoded.
286 * NOTE: This function checks for 5-Byte sequences, UTF8
287 * has Bytes Sequences with a maximum length of 4.
289 * @author bmorel at ssi dot fr (modified)
292 * @param string $str The string to be checked
293 * @return bool True if $str fits a UTF-8 model, false otherwise.
295 function seems_utf8($str) {
296 $length = strlen($str);
297 for ($i=0; $i < $length; $i++) {
299 if ($c < 0x80) $n = 0; # 0bbbbbbb
300 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
301 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
302 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
303 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
304 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
305 else return false; # Does not match any model
306 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
307 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
315 * Converts a number of special characters into their HTML entities.
317 * Specifically deals with: &, <, >, ", and '.
319 * $quote_style can be set to ENT_COMPAT to encode " to
320 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
324 * @param string $string The text which is to be encoded.
325 * @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.
326 * @param string $charset Optional. The character encoding of the string. Default is false.
327 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
328 * @return string The encoded text with HTML entities.
330 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
331 $string = (string) $string;
333 if ( 0 === strlen( $string ) )
336 // Don't bother if there are no specialchars - saves some processing
337 if ( ! preg_match( '/[&<>"\']/', $string ) )
340 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
341 if ( empty( $quote_style ) )
342 $quote_style = ENT_NOQUOTES;
343 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
344 $quote_style = ENT_QUOTES;
346 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
349 if ( ! isset( $_charset ) ) {
350 $alloptions = wp_load_alloptions();
351 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
353 $charset = $_charset;
356 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
359 $_quote_style = $quote_style;
361 if ( $quote_style === 'double' ) {
362 $quote_style = ENT_COMPAT;
363 $_quote_style = ENT_COMPAT;
364 } elseif ( $quote_style === 'single' ) {
365 $quote_style = ENT_NOQUOTES;
368 // Handle double encoding ourselves
369 if ( $double_encode ) {
370 $string = @htmlspecialchars( $string, $quote_style, $charset );
372 // Decode & into &
373 $string = wp_specialchars_decode( $string, $_quote_style );
375 // Guarantee every &entity; is valid or re-encode the &
376 $string = wp_kses_normalize_entities( $string );
378 // Now re-encode everything except &entity;
379 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
381 for ( $i = 0; $i < count( $string ); $i += 2 )
382 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
384 $string = implode( '', $string );
387 // Backwards compatibility
388 if ( 'single' === $_quote_style )
389 $string = str_replace( "'", ''', $string );
395 * Converts a number of HTML entities into their special characters.
397 * Specifically deals with: &, <, >, ", and '.
399 * $quote_style can be set to ENT_COMPAT to decode " entities,
400 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
404 * @param string $string The text which is to be decoded.
405 * @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.
406 * @return string The decoded text without HTML entities.
408 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
409 $string = (string) $string;
411 if ( 0 === strlen( $string ) ) {
415 // Don't bother if there are no entities - saves a lot of processing
416 if ( strpos( $string, '&' ) === false ) {
420 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
421 if ( empty( $quote_style ) ) {
422 $quote_style = ENT_NOQUOTES;
423 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
424 $quote_style = ENT_QUOTES;
427 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
428 $single = array( ''' => '\'', ''' => '\'' );
429 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
430 $double = array( '"' => '"', '"' => '"', '"' => '"' );
431 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
432 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
433 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
435 if ( $quote_style === ENT_QUOTES ) {
436 $translation = array_merge( $single, $double, $others );
437 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
438 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
439 $translation = array_merge( $double, $others );
440 $translation_preg = array_merge( $double_preg, $others_preg );
441 } elseif ( $quote_style === 'single' ) {
442 $translation = array_merge( $single, $others );
443 $translation_preg = array_merge( $single_preg, $others_preg );
444 } elseif ( $quote_style === ENT_NOQUOTES ) {
445 $translation = $others;
446 $translation_preg = $others_preg;
449 // Remove zero padding on numeric entities
450 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
452 // Replace characters according to translation table
453 return strtr( $string, $translation );
457 * Checks for invalid UTF8 in a string.
461 * @param string $string The text which is to be checked.
462 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
463 * @return string The checked text.
465 function wp_check_invalid_utf8( $string, $strip = false ) {
466 $string = (string) $string;
468 if ( 0 === strlen( $string ) ) {
472 // Store the site charset as a static to avoid multiple calls to get_option()
474 if ( !isset( $is_utf8 ) ) {
475 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
481 // Check for support for utf8 in the installed PCRE library once and store the result in a static
483 if ( !isset( $utf8_pcre ) ) {
484 $utf8_pcre = @preg_match( '/^./u', 'a' );
486 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
491 // preg_match fails when it encounters invalid UTF8 in $string
492 if ( 1 === @preg_match( '/^./us', $string ) ) {
496 // Attempt to strip the bad chars if requested (not recommended)
497 if ( $strip && function_exists( 'iconv' ) ) {
498 return iconv( 'utf-8', 'utf-8', $string );
505 * Encode the Unicode values to be used in the URI.
509 * @param string $utf8_string
510 * @param int $length Max length of the string
511 * @return string String with Unicode encoded for URI.
513 function utf8_uri_encode( $utf8_string, $length = 0 ) {
519 $string_length = strlen( $utf8_string );
520 for ($i = 0; $i < $string_length; $i++ ) {
522 $value = ord( $utf8_string[ $i ] );
524 if ( $value < 128 ) {
525 if ( $length && ( $unicode_length >= $length ) )
527 $unicode .= chr($value);
530 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
534 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
536 if ( count( $values ) == $num_octets ) {
537 if ($num_octets == 3) {
538 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
539 $unicode_length += 9;
541 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
542 $unicode_length += 6;
555 * Converts all accent characters to ASCII characters.
557 * If there are no accent characters, then the string given is just returned.
561 * @param string $string Text that might have accent characters
562 * @return string Filtered string with replaced "nice" characters.
564 function remove_accents($string) {
565 if ( !preg_match('/[\x80-\xff]/', $string) )
568 if (seems_utf8($string)) {
570 // Decompositions for Latin-1 Supplement
571 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
572 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
573 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
574 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
575 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
576 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
577 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
578 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
579 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
580 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
581 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
582 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
583 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
584 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
585 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
586 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
587 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
588 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
589 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
590 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
591 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
592 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
593 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
594 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
595 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
596 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
597 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
598 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
599 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
600 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
601 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
602 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
603 // Decompositions for Latin Extended-A
604 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
605 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
606 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
607 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
608 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
609 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
610 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
611 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
612 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
613 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
614 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
615 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
616 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
617 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
618 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
619 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
620 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
621 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
622 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
623 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
624 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
625 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
626 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
627 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
628 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
629 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
630 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
631 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
632 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
633 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
634 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
635 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
636 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
637 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
638 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
639 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
640 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
641 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
642 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
643 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
644 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
645 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
646 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
647 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
648 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
649 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
650 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
651 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
652 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
653 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
654 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
655 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
656 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
657 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
658 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
659 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
660 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
661 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
662 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
663 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
664 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
665 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
666 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
667 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
668 // Decompositions for Latin Extended-B
669 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
670 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
672 chr(226).chr(130).chr(172) => 'E',
674 chr(194).chr(163) => '');
676 $string = strtr($string, $chars);
678 // Assume ISO-8859-1 if not UTF-8
679 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
680 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
681 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
682 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
683 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
684 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
685 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
686 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
687 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
688 .chr(252).chr(253).chr(255);
690 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
692 $string = strtr($string, $chars['in'], $chars['out']);
693 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
694 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
695 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
702 * Sanitizes a filename replacing whitespace with dashes
704 * Removes special characters that are illegal in filenames on certain
705 * operating systems and special characters requiring special escaping
706 * to manipulate at the command line. Replaces spaces and consecutive
707 * dashes with a single dash. Trim period, dash and underscore from beginning
708 * and end of filename.
712 * @param string $filename The filename to be sanitized
713 * @return string The sanitized filename
715 function sanitize_file_name( $filename ) {
716 $filename_raw = $filename;
717 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
718 $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
719 $filename = str_replace($special_chars, '', $filename);
720 $filename = preg_replace('/[\s-]+/', '-', $filename);
721 $filename = trim($filename, '.-_');
723 // Split the filename into a base and extension[s]
724 $parts = explode('.', $filename);
726 // Return if only one extension
727 if ( count($parts) <= 2 )
728 return apply_filters('sanitize_file_name', $filename, $filename_raw);
730 // Process multiple extensions
731 $filename = array_shift($parts);
732 $extension = array_pop($parts);
733 $mimes = get_allowed_mime_types();
735 // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
736 // long alpha string not in the extension whitelist.
737 foreach ( (array) $parts as $part) {
738 $filename .= '.' . $part;
740 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
742 foreach ( $mimes as $ext_preg => $mime_match ) {
743 $ext_preg = '!^(' . $ext_preg . ')$!i';
744 if ( preg_match( $ext_preg, $part ) ) {
753 $filename .= '.' . $extension;
755 return apply_filters('sanitize_file_name', $filename, $filename_raw);
759 * Sanitize username stripping out unsafe characters.
761 * Removes tags, octets, entities, and if strict is enabled, will only keep
762 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
763 * raw username (the username in the parameter), and the value of $strict as
764 * parameters for the 'sanitize_user' filter.
767 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
768 * and $strict parameter.
770 * @param string $username The username to be sanitized.
771 * @param bool $strict If set limits $username to specific characters. Default false.
772 * @return string The sanitized username, after passing through filters.
774 function sanitize_user( $username, $strict = false ) {
775 $raw_username = $username;
776 $username = wp_strip_all_tags( $username );
777 $username = remove_accents( $username );
779 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
780 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
782 // If strict, reduce to ASCII for max portability.
784 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
786 $username = trim( $username );
787 // Consolidate contiguous whitespace
788 $username = preg_replace( '|\s+|', ' ', $username );
790 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
794 * Sanitize a string key.
796 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
800 * @param string $key String key
801 * @return string Sanitized key
803 function sanitize_key( $key ) {
805 $key = strtolower( $key );
806 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
807 return apply_filters( 'sanitize_key', $key, $raw_key );
811 * Sanitizes title or use fallback title.
813 * Specifically, HTML and PHP tags are stripped. Further actions can be added
814 * via the plugin API. If $title is empty and $fallback_title is set, the latter
819 * @param string $title The string to be sanitized.
820 * @param string $fallback_title Optional. A title to use if $title is empty.
821 * @param string $context Optional. The operation for which the string is sanitized
822 * @return string The sanitized string.
824 function sanitize_title($title, $fallback_title = '', $context = 'save') {
827 if ( 'save' == $context )
828 $title = remove_accents($title);
830 $title = apply_filters('sanitize_title', $title, $raw_title, $context);
832 if ( '' === $title || false === $title )
833 $title = $fallback_title;
838 function sanitize_title_for_query($title) {
839 return sanitize_title($title, '', 'query');
843 * Sanitizes title, replacing whitespace and a few other characters with dashes.
845 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
846 * Whitespace becomes a dash.
850 * @param string $title The title to be sanitized.
851 * @param string $raw_title Optional. Not used.
852 * @param string $context Optional. The operation for which the string is sanitized.
853 * @return string The sanitized title.
855 function sanitize_title_with_dashes($title, $raw_title = '', $context = 'display') {
856 $title = strip_tags($title);
857 // Preserve escaped octets.
858 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
859 // Remove percent signs that are not part of an octet.
860 $title = str_replace('%', '', $title);
862 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
864 if (seems_utf8($title)) {
865 if (function_exists('mb_strtolower')) {
866 $title = mb_strtolower($title, 'UTF-8');
868 $title = utf8_uri_encode($title, 200);
871 $title = strtolower($title);
872 $title = preg_replace('/&.+?;/', '', $title); // kill entities
873 $title = str_replace('.', '-', $title);
875 if ( 'save' == $context ) {
876 // nbsp, ndash and mdash
877 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
879 $title = str_replace( array( '%c2%a1', '%c2%bf' ), '', $title );
881 $title = str_replace( array( '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba' ), '', $title );
883 $title = str_replace( array( '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d' ), '', $title );
884 // copy, reg, deg, hellip and trade
885 $title = str_replace( array( '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2' ), '', $title );
888 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
889 $title = preg_replace('/\s+/', '-', $title);
890 $title = preg_replace('|-+|', '-', $title);
891 $title = trim($title, '-');
897 * Ensures a string is a valid SQL order by clause.
899 * Accepts one or more columns, with or without ASC/DESC, and also accepts
904 * @param string $orderby Order by string to be checked.
905 * @return string|false Returns the order by clause if it is a match, false otherwise.
907 function sanitize_sql_orderby( $orderby ){
908 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
915 * Santizes a html classname to ensure it only contains valid characters
917 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
918 * string then it will return the alternative value supplied.
920 * @todo Expand to support the full range of CDATA that a class attribute can contain.
924 * @param string $class The classname to be sanitized
925 * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
926 * Defaults to an empty string.
927 * @return string The sanitized value
929 function sanitize_html_class( $class, $fallback = '' ) {
930 //Strip out any % encoded octets
931 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
933 //Limit to A-Z,a-z,0-9,_,-
934 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
936 if ( '' == $sanitized )
937 $sanitized = $fallback;
939 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
943 * Converts a number of characters from a string.
945 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
946 * converted into correct XHTML and Unicode characters are converted to the
951 * @param string $content String of characters to be converted.
952 * @param string $deprecated Not used.
953 * @return string Converted string.
955 function convert_chars($content, $deprecated = '') {
956 if ( !empty( $deprecated ) )
957 _deprecated_argument( __FUNCTION__, '0.71' );
959 // Translation of invalid Unicode references range to valid range
960 $wp_htmltranswinuni = array(
961 '€' => '€', // the Euro sign
963 '‚' => '‚', // these are Windows CP1252 specific characters
964 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
965 '„' => '„',
966 '…' => '…',
967 '†' => '†',
968 '‡' => '‡',
969 'ˆ' => 'ˆ',
970 '‰' => '‰',
971 'Š' => 'Š',
972 '‹' => '‹',
973 'Œ' => 'Œ',
975 'Ž' => 'ž',
978 '‘' => '‘',
979 '’' => '’',
980 '“' => '“',
981 '”' => '”',
982 '•' => '•',
983 '–' => '–',
984 '—' => '—',
985 '˜' => '˜',
986 '™' => '™',
987 'š' => 'š',
988 '›' => '›',
989 'œ' => 'œ',
995 // Remove metadata tags
996 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
997 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
999 // Converts lone & characters into & (a.k.a. &)
1000 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1003 $content = strtr($content, $wp_htmltranswinuni);
1005 // Just a little XHTML help
1006 $content = str_replace('<br>', '<br />', $content);
1007 $content = str_replace('<hr>', '<hr />', $content);
1013 * Will only balance the tags if forced to and the option is set to balance tags.
1015 * The option 'use_balanceTags' is used for whether the tags will be balanced.
1016 * Both the $force parameter and 'use_balanceTags' option will have to be true
1017 * before the tags will be balanced.
1021 * @param string $text Text to be balanced
1022 * @param bool $force Forces balancing, ignoring the value of the option. Default false.
1023 * @return string Balanced text
1025 function balanceTags( $text, $force = false ) {
1026 if ( !$force && get_option('use_balanceTags') == 0 )
1028 return force_balance_tags( $text );
1032 * Balances tags of string using a modified stack.
1036 * @author Leonard Lin <leonard@acm.org>
1038 * @copyright November 4, 2001
1040 * @todo Make better - change loop condition to $text in 1.2
1041 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1042 * 1.1 Fixed handling of append/stack pop order of end text
1043 * Added Cleaning Hooks
1046 * @param string $text Text to be balanced.
1047 * @return string Balanced text.
1049 function force_balance_tags( $text ) {
1050 $tagstack = array();
1054 $single_tags = array( 'br', 'hr', 'img', 'input' ); // Known single-entity/self-closing tags
1055 $nestable_tags = array( 'blockquote', 'div', 'span', 'q' ); // Tags that can be immediately nested within themselves
1057 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1058 $text = str_replace('< !--', '< !--', $text);
1059 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1060 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1062 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1063 $newtext .= $tagqueue;
1065 $i = strpos($text, $regex[0]);
1066 $l = strlen($regex[0]);
1068 // clear the shifter
1071 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1072 $tag = strtolower(substr($regex[1],1));
1073 // if too many closing tags
1074 if( $stacksize <= 0 ) {
1076 // or close to be safe $tag = '/' . $tag;
1078 // if stacktop value = tag close value then pop
1079 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1080 $tag = '</' . $tag . '>'; // Close Tag
1082 array_pop( $tagstack );
1084 } else { // closing tag not at top, search for it
1085 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1086 if ( $tagstack[$j] == $tag ) {
1087 // add tag to tagqueue
1088 for ( $k = $stacksize-1; $k >= $j; $k--) {
1089 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1097 } else { // Begin Tag
1098 $tag = strtolower($regex[1]);
1102 // If self-closing or '', don't do anything.
1103 if ( substr($regex[2],-1) == '/' || $tag == '' ) {
1106 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1107 elseif ( in_array($tag, $single_tags) ) {
1109 } else { // Push the tag onto the stack
1110 // If the top of the stack is the same as the tag we want to push, close previous tag
1111 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1112 $tagqueue = '</' . array_pop ($tagstack) . '>';
1115 $stacksize = array_push ($tagstack, $tag);
1119 $attributes = $regex[2];
1120 if( !empty($attributes) )
1121 $attributes = ' '.$attributes;
1123 $tag = '<' . $tag . $attributes . '>';
1124 //If already queuing a close tag, then put this tag on, too
1125 if ( !empty($tagqueue) ) {
1130 $newtext .= substr($text, 0, $i) . $tag;
1131 $text = substr($text, $i + $l);
1135 $newtext .= $tagqueue;
1137 // Add Remaining text
1141 while( $x = array_pop($tagstack) )
1142 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1144 // WP fix for the bug with HTML comments
1145 $newtext = str_replace("< !--","<!--",$newtext);
1146 $newtext = str_replace("< !--","< !--",$newtext);
1152 * Acts on text which is about to be edited.
1154 * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
1155 * filter. If $richedit is set true htmlspecialchars(), through esc_textarea(),
1156 * will be run on the content, converting special characters to HTML entities.
1160 * @param string $content The text about to be edited.
1161 * @param bool $richedit Whether the $content should pass through htmlspecialchars(). Default false.
1162 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1164 function format_to_edit( $content, $richedit = false ) {
1165 $content = apply_filters( 'format_to_edit', $content );
1167 $content = esc_textarea( $content );
1172 * Holder for the 'format_to_post' filter.
1176 * @param string $content The text to pass through the filter.
1177 * @return string Text returned from the 'format_to_post' filter.
1179 function format_to_post($content) {
1180 $content = apply_filters('format_to_post', $content);
1185 * Add leading zeros when necessary.
1187 * If you set the threshold to '4' and the number is '10', then you will get
1188 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1189 * will get back '5000'.
1191 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1192 * and the size of the number. If the number is large enough, then no zeros will
1197 * @param mixed $number Number to append zeros to if not greater than threshold.
1198 * @param int $threshold Digit places number needs to be to not have zeros added.
1199 * @return string Adds leading zeros to number if needed.
1201 function zeroise($number, $threshold) {
1202 return sprintf('%0'.$threshold.'s', $number);
1206 * Adds backslashes before letters and before a number at the start of a string.
1210 * @param string $string Value to which backslashes will be added.
1211 * @return string String with backslashes inserted.
1213 function backslashit($string) {
1214 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1215 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1220 * Appends a trailing slash.
1222 * Will remove trailing slash if it exists already before adding a trailing
1223 * slash. This prevents double slashing a string or path.
1225 * The primary use of this is for paths and thus should be used for paths. It is
1226 * not restricted to paths and offers no specific path support.
1229 * @uses untrailingslashit() Unslashes string if it was slashed already.
1231 * @param string $string What to add the trailing slash to.
1232 * @return string String with trailing slash added.
1234 function trailingslashit($string) {
1235 return untrailingslashit($string) . '/';
1239 * Removes trailing slash if it exists.
1241 * The primary use of this is for paths and thus should be used for paths. It is
1242 * not restricted to paths and offers no specific path support.
1246 * @param string $string What to remove the trailing slash from.
1247 * @return string String without the trailing slash.
1249 function untrailingslashit($string) {
1250 return rtrim($string, '/');
1254 * Adds slashes to escape strings.
1256 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1257 * http://www.php.net/magic_quotes} for more details.
1261 * @param string $gpc The string returned from HTTP request data.
1262 * @return string Returns a string escaped with slashes.
1264 function addslashes_gpc($gpc) {
1265 if ( get_magic_quotes_gpc() )
1266 $gpc = stripslashes($gpc);
1268 return esc_sql($gpc);
1272 * Navigates through an array and removes slashes from the values.
1274 * If an array is passed, the array_map() function causes a callback to pass the
1275 * value back to the function. The slashes from this value will removed.
1279 * @param array|string $value The array or string to be stripped.
1280 * @return array|string Stripped array (or string in the callback).
1282 function stripslashes_deep($value) {
1283 if ( is_array($value) ) {
1284 $value = array_map('stripslashes_deep', $value);
1285 } elseif ( is_object($value) ) {
1286 $vars = get_object_vars( $value );
1287 foreach ($vars as $key=>$data) {
1288 $value->{$key} = stripslashes_deep( $data );
1291 $value = stripslashes($value);
1298 * Navigates through an array and encodes the values to be used in a URL.
1300 * Uses a callback to pass the value of the array back to the function as a
1305 * @param array|string $value The array or string to be encoded.
1306 * @return array|string $value The encoded array (or string from the callback).
1308 function urlencode_deep($value) {
1309 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1314 * Converts email addresses characters to HTML entities to block spam bots.
1318 * @param string $emailaddy Email address.
1319 * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1320 * @return string Converted email address.
1322 function antispambot($emailaddy, $mailto=0) {
1323 $emailNOSPAMaddy = '';
1324 srand ((float) microtime() * 1000000);
1325 for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1326 $j = floor(rand(0, 1+$mailto));
1328 $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1330 $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1332 $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1335 $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy);
1336 return $emailNOSPAMaddy;
1340 * Callback to convert URI match to HTML A element.
1342 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1343 * make_clickable()}.
1348 * @param array $matches Single Regex Match.
1349 * @return string HTML A element with URI address.
1351 function _make_url_clickable_cb($matches) {
1355 /** Include parentheses in the URL only if paired **/
1356 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1357 $suffix = strrchr( $url, ')' ) . $suffix;
1358 $url = substr( $url, 0, strrpos( $url, ')' ) );
1361 $url = esc_url($url);
1365 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1369 * Callback to convert URL match to HTML A element.
1371 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1372 * make_clickable()}.
1377 * @param array $matches Single Regex Match.
1378 * @return string HTML A element with URL address.
1380 function _make_web_ftp_clickable_cb($matches) {
1382 $dest = $matches[2];
1383 $dest = 'http://' . $dest;
1384 $dest = esc_url($dest);
1388 // removed trailing [.,;:)] from URL
1389 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1390 $ret = substr($dest, -1);
1391 $dest = substr($dest, 0, strlen($dest)-1);
1393 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1397 * Callback to convert email address match to HTML A element.
1399 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1400 * make_clickable()}.
1405 * @param array $matches Single Regex Match.
1406 * @return string HTML A element with email address.
1408 function _make_email_clickable_cb($matches) {
1409 $email = $matches[2] . '@' . $matches[3];
1410 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1414 * Convert plaintext URI to HTML links.
1416 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1421 * @param string $ret Content to convert URIs.
1422 * @return string Content with converted URIs.
1424 function make_clickable($ret) {
1426 // in testing, using arrays here was found to be faster
1427 $save = @ini_set('pcre.recursion_limit', 10000);
1428 $retval = preg_replace_callback('#(?<!=[\'"])(?<=[*\')+.,;:!&$\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#%~/?@\[\]-]{1,2000}|[\'*(+.,;:!=&$](?![\b\)]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
1429 if (null !== $retval )
1431 @ini_set('pcre.recursion_limit', $save);
1432 $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1433 $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1434 // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1435 $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1441 * Adds rel nofollow string to all HTML A elements in content.
1445 * @param string $text Content that may contain HTML A elements.
1446 * @return string Converted content.
1448 function wp_rel_nofollow( $text ) {
1449 // This is a pre save filter, so text is already escaped.
1450 $text = stripslashes($text);
1451 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1452 $text = esc_sql($text);
1457 * Callback to used to add rel=nofollow string to HTML A element.
1459 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1460 * string to prevent from invalidating (X)HTML.
1464 * @param array $matches Single Match
1465 * @return string HTML A Element with rel nofollow.
1467 function wp_rel_nofollow_callback( $matches ) {
1468 $text = $matches[1];
1469 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1470 return "<a $text rel=\"nofollow\">";
1474 * Convert one smiley code to the icon graphic file equivalent.
1476 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1477 * <img> string for that smiley.
1479 * @global array $wpsmiliestrans
1482 * @param string $smiley Smiley code to convert to image.
1483 * @return string Image string for smiley.
1485 function translate_smiley($smiley) {
1486 global $wpsmiliestrans;
1488 if (count($smiley) == 0) {
1492 $smiley = trim(reset($smiley));
1493 $img = $wpsmiliestrans[$smiley];
1494 $smiley_masked = esc_attr($smiley);
1496 $srcurl = apply_filters('smilies_src', includes_url("images/smilies/$img"), $img, site_url());
1498 return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1502 * Convert text equivalent of smilies to images.
1504 * Will only convert smilies if the option 'use_smilies' is true and the global
1505 * used in the function isn't empty.
1508 * @uses $wp_smiliessearch
1510 * @param string $text Content to convert smilies from text.
1511 * @return string Converted content with text smilies replaced with images.
1513 function convert_smilies($text) {
1514 global $wp_smiliessearch;
1516 if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1517 // HTML loop taken from texturize function, could possible be consolidated
1518 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1519 $stop = count($textarr);// loop stuff
1520 for ($i = 0; $i < $stop; $i++) {
1521 $content = $textarr[$i];
1522 if ((strlen($content) > 0) && ('<' != $content[0])) { // If it's not a tag
1523 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1525 $output .= $content;
1528 // return default text.
1535 * Verifies that an email is valid.
1537 * Does not grok i18n domains. Not RFC compliant.
1541 * @param string $email Email address to verify.
1542 * @param boolean $deprecated Deprecated.
1543 * @return string|bool Either false or the valid email address.
1545 function is_email( $email, $deprecated = false ) {
1546 if ( ! empty( $deprecated ) )
1547 _deprecated_argument( __FUNCTION__, '3.0' );
1549 // Test for the minimum length the email can be
1550 if ( strlen( $email ) < 3 ) {
1551 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1554 // Test for an @ character after the first position
1555 if ( strpos( $email, '@', 1 ) === false ) {
1556 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1559 // Split out the local and domain parts
1560 list( $local, $domain ) = explode( '@', $email, 2 );
1563 // Test for invalid characters
1564 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1565 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1569 // Test for sequences of periods
1570 if ( preg_match( '/\.{2,}/', $domain ) ) {
1571 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1574 // Test for leading and trailing periods and whitespace
1575 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1576 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1579 // Split the domain into subs
1580 $subs = explode( '.', $domain );
1582 // Assume the domain will have at least two subs
1583 if ( 2 > count( $subs ) ) {
1584 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1587 // Loop through each sub
1588 foreach ( $subs as $sub ) {
1589 // Test for leading and trailing hyphens and whitespace
1590 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1591 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1594 // Test for invalid characters
1595 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1596 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1600 // Congratulations your email made it!
1601 return apply_filters( 'is_email', $email, $email, null );
1605 * Convert to ASCII from email subjects.
1608 * @usedby wp_mail() handles charsets in email subjects
1610 * @param string $string Subject line
1611 * @return string Converted string to ASCII
1613 function wp_iso_descrambler($string) {
1614 /* this may only work with iso-8859-1, I'm afraid */
1615 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1618 $subject = str_replace('_', ' ', $matches[2]);
1619 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
1625 * Helper function to convert hex encoded chars to ascii
1629 * @param array $match the preg_replace_callback matches array
1631 function _wp_iso_convert( $match ) {
1632 return chr( hexdec( strtolower( $match[1] ) ) );
1636 * Returns a date in the GMT equivalent.
1638 * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1639 * value of the 'gmt_offset' option. Return format can be overridden using the
1640 * $format parameter. The DateTime and DateTimeZone classes are used to respect
1641 * time zone differences in DST.
1645 * @uses get_option() to retrieve the the value of 'gmt_offset'.
1646 * @param string $string The date to be converted.
1647 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1648 * @return string GMT version of the date provided.
1650 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1651 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);
1652 $tz = get_option('timezone_string');
1654 date_default_timezone_set( $tz );
1655 $datetime = new DateTime( $string );
1656 $datetime->setTimezone( new DateTimeZone('UTC') );
1657 $offset = $datetime->getOffset();
1658 $datetime->modify( '+' . $offset / 3600 . ' hours');
1659 $string_gmt = gmdate($format, $datetime->format('U'));
1661 date_default_timezone_set('UTC');
1663 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1664 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1670 * Converts a GMT date into the correct format for the blog.
1672 * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1673 * gmt_offset.Return format can be overridden using the $format parameter
1677 * @param string $string The date to be converted.
1678 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1679 * @return string Formatted date relative to the GMT offset.
1681 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1682 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);
1683 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1684 $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1685 return $string_localtime;
1689 * Computes an offset in seconds from an iso8601 timezone.
1693 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1694 * @return int|float The offset in seconds.
1696 function iso8601_timezone_to_offset($timezone) {
1697 // $timezone is either 'Z' or '[+|-]hhmm'
1698 if ($timezone == 'Z') {
1701 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1702 $hours = intval(substr($timezone, 1, 2));
1703 $minutes = intval(substr($timezone, 3, 4)) / 60;
1704 $offset = $sign * 3600 * ($hours + $minutes);
1710 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1714 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1715 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1716 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1718 function iso8601_to_datetime($date_string, $timezone = 'user') {
1719 $timezone = strtolower($timezone);
1721 if ($timezone == 'gmt') {
1723 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);
1725 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1726 $offset = iso8601_timezone_to_offset($date_bits[7]);
1727 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1728 $offset = 3600 * get_option('gmt_offset');
1731 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1732 $timestamp -= $offset;
1734 return gmdate('Y-m-d H:i:s', $timestamp);
1736 } else if ($timezone == 'user') {
1737 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);
1742 * Adds a element attributes to open links in new windows.
1744 * Comment text in popup windows should be filtered through this. Right now it's
1745 * a moderately dumb function, ideally it would detect whether a target or rel
1746 * attribute was already there and adjust its actions accordingly.
1750 * @param string $text Content to replace links to open in a new window.
1751 * @return string Content that has filtered links.
1753 function popuplinks($text) {
1754 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1759 * Strips out all characters that are not allowable in an email.
1763 * @param string $email Email address to filter.
1764 * @return string Filtered email address.
1766 function sanitize_email( $email ) {
1767 // Test for the minimum length the email can be
1768 if ( strlen( $email ) < 3 ) {
1769 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1772 // Test for an @ character after the first position
1773 if ( strpos( $email, '@', 1 ) === false ) {
1774 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1777 // Split out the local and domain parts
1778 list( $local, $domain ) = explode( '@', $email, 2 );
1781 // Test for invalid characters
1782 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1783 if ( '' === $local ) {
1784 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1788 // Test for sequences of periods
1789 $domain = preg_replace( '/\.{2,}/', '', $domain );
1790 if ( '' === $domain ) {
1791 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1794 // Test for leading and trailing periods and whitespace
1795 $domain = trim( $domain, " \t\n\r\0\x0B." );
1796 if ( '' === $domain ) {
1797 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1800 // Split the domain into subs
1801 $subs = explode( '.', $domain );
1803 // Assume the domain will have at least two subs
1804 if ( 2 > count( $subs ) ) {
1805 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1808 // Create an array that will contain valid subs
1809 $new_subs = array();
1811 // Loop through each sub
1812 foreach ( $subs as $sub ) {
1813 // Test for leading and trailing hyphens
1814 $sub = trim( $sub, " \t\n\r\0\x0B-" );
1816 // Test for invalid characters
1817 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
1819 // If there's anything left, add it to the valid subs
1820 if ( '' !== $sub ) {
1825 // If there aren't 2 or more valid subs
1826 if ( 2 > count( $new_subs ) ) {
1827 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1830 // Join valid subs into the new domain
1831 $domain = join( '.', $new_subs );
1833 // Put the email back together
1834 $email = $local . '@' . $domain;
1836 // Congratulations your email made it!
1837 return apply_filters( 'sanitize_email', $email, $email, null );
1841 * Determines the difference between two timestamps.
1843 * The difference is returned in a human readable format such as "1 hour",
1844 * "5 mins", "2 days".
1848 * @param int $from Unix timestamp from which the difference begins.
1849 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1850 * @return string Human readable time difference.
1852 function human_time_diff( $from, $to = '' ) {
1855 $diff = (int) abs($to - $from);
1856 if ($diff <= 3600) {
1857 $mins = round($diff / 60);
1861 /* translators: min=minute */
1862 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1863 } else if (($diff <= 86400) && ($diff > 3600)) {
1864 $hours = round($diff / 3600);
1868 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1869 } elseif ($diff >= 86400) {
1870 $days = round($diff / 86400);
1874 $since = sprintf(_n('%s day', '%s days', $days), $days);
1880 * Generates an excerpt from the content, if needed.
1882 * The excerpt word amount will be 55 words and if the amount is greater than
1883 * that, then the string ' [...]' will be appended to the excerpt. If the string
1884 * is less than 55 words, then the content will be returned as is.
1886 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
1887 * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
1891 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
1892 * @return string The excerpt.
1894 function wp_trim_excerpt($text = '') {
1895 $raw_excerpt = $text;
1896 if ( '' == $text ) {
1897 $text = get_the_content('');
1899 $text = strip_shortcodes( $text );
1901 $text = apply_filters('the_content', $text);
1902 $text = str_replace(']]>', ']]>', $text);
1903 $excerpt_length = apply_filters('excerpt_length', 55);
1904 $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
1905 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
1907 return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1911 * Trims text to a certain number of words.
1915 * @param string $text Text to trim.
1916 * @param int $num_words Number of words. Default 55.
1917 * @param string $more What to append if $text needs to be trimmed. Default '…'.
1918 * @return string Trimmed text.
1920 function wp_trim_words( $text, $num_words = 55, $more = null ) {
1921 if ( null === $more )
1922 $more = __( '…' );
1923 $original_text = $text;
1924 $text = wp_strip_all_tags( $text );
1925 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
1926 if ( count( $words_array ) > $num_words ) {
1927 array_pop( $words_array );
1928 $text = implode( ' ', $words_array );
1929 $text = $text . $more;
1931 $text = implode( ' ', $words_array );
1933 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
1937 * Converts named entities into numbered entities.
1941 * @param string $text The text within which entities will be converted.
1942 * @return string Text with converted entities.
1944 function ent2ncr($text) {
1946 // Allow a plugin to short-circuit and override the mappings.
1947 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
1948 if( null !== $filtered )
1952 '"' => '"',
1954 '⁄' => '/',
1958 ' ' => ' ',
1959 '¡' => '¡',
1960 '¢' => '¢',
1961 '£' => '£',
1962 '¤' => '¤',
1963 '¥' => '¥',
1964 '¦' => '¦',
1965 '&brkbar;' => '¦',
1966 '§' => '§',
1967 '¨' => '¨',
1968 '¨' => '¨',
1969 '©' => '©',
1970 'ª' => 'ª',
1971 '«' => '«',
1972 '¬' => '¬',
1973 '­' => '­',
1974 '®' => '®',
1975 '¯' => '¯',
1976 '&hibar;' => '¯',
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 'Ó' => 'Ó',
2013 'Ô' => 'Ô',
2014 'Õ' => 'Õ',
2015 'Ö' => 'Ö',
2016 '×' => '×',
2017 'Ø' => 'Ø',
2018 'Ù' => 'Ù',
2019 'Ú' => 'Ú',
2020 'Û' => 'Û',
2021 'Ü' => 'Ü',
2022 'Ý' => 'Ý',
2023 'Þ' => 'Þ',
2024 'ß' => 'ß',
2025 'à' => 'à',
2026 'á' => 'á',
2027 'â' => 'â',
2028 'ã' => 'ã',
2029 'ä' => 'ä',
2030 'å' => 'å',
2031 'æ' => 'æ',
2032 'ç' => 'ç',
2033 'è' => 'è',
2034 'é' => 'é',
2035 'ê' => 'ê',
2036 'ë' => 'ë',
2037 'ì' => 'ì',
2038 'í' => 'í',
2039 'î' => 'î',
2040 'ï' => 'ï',
2041 'ð' => 'ð',
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 'Λ' => 'Λ',
2079 'Ο' => 'Ο',
2081 'Ρ' => 'Ρ',
2082 'Σ' => 'Σ',
2083 'Τ' => 'Τ',
2084 'Υ' => 'Υ',
2085 'Φ' => 'Φ',
2086 'Χ' => 'Χ',
2087 'Ψ' => 'Ψ',
2088 'Ω' => 'Ω',
2089 'α' => 'α',
2090 'β' => 'β',
2091 'γ' => 'γ',
2092 'δ' => 'δ',
2093 'ε' => 'ε',
2094 'ζ' => 'ζ',
2095 'η' => 'η',
2096 'θ' => 'θ',
2097 'ι' => 'ι',
2098 'κ' => 'κ',
2099 'λ' => 'λ',
2103 'ο' => 'ο',
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 '℘' => '℘',
2146 'ℜ' => 'ℜ',
2147 '™' => '™',
2148 'ℵ' => 'ℵ',
2149 '↵' => '↵',
2150 '⇐' => '⇐',
2151 '⇑' => '⇑',
2152 '⇒' => '⇒',
2153 '⇓' => '⇓',
2154 '⇔' => '⇔',
2155 '∀' => '∀',
2156 '∂' => '∂',
2157 '∃' => '∃',
2158 '∅' => '∅',
2159 '∇' => '∇',
2160 '∈' => '∈',
2161 '∉' => '∉',
2162 '∋' => '∋',
2163 '∏' => '∏',
2164 '∑' => '∑',
2165 '−' => '−',
2166 '∗' => '∗',
2167 '√' => '√',
2168 '∝' => '∝',
2169 '∞' => '∞',
2170 '∠' => '∠',
2171 '∧' => '∧',
2172 '∨' => '∨',
2173 '∩' => '∩',
2174 '∪' => '∪',
2175 '∫' => '∫',
2176 '∴' => '∴',
2177 '∼' => '∼',
2178 '≅' => '≅',
2179 '≈' => '≈',
2180 '≠' => '≠',
2181 '≡' => '≡',
2182 '≤' => '≤',
2183 '≥' => '≥',
2184 '⊂' => '⊂',
2185 '⊃' => '⊃',
2186 '⊄' => '⊄',
2187 '⊆' => '⊆',
2188 '⊇' => '⊇',
2189 '⊕' => '⊕',
2190 '⊗' => '⊗',
2191 '⊥' => '⊥',
2192 '⋅' => '⋅',
2193 '⌈' => '⌈',
2194 '⌉' => '⌉',
2195 '⌊' => '⌊',
2196 '⌋' => '⌋',
2197 '⟨' => '〈',
2198 '⟩' => '〉',
2199 '←' => '←',
2200 '↑' => '↑',
2201 '→' => '→',
2202 '↓' => '↓',
2203 '↔' => '↔',
2204 '◊' => '◊',
2205 '♠' => '♠',
2206 '♣' => '♣',
2207 '♥' => '♥',
2208 '♦' => '♦'
2211 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2215 * Formats text for the rich text editor.
2217 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2218 * be applied to an empty string.
2222 * @param string $text The text to be formatted.
2223 * @return string The formatted text after filter is applied.
2225 function wp_richedit_pre($text) {
2226 // Filtering a blank results in an annoying <br />\n
2227 if ( empty($text) ) return apply_filters('richedit_pre', '');
2229 $output = convert_chars($text);
2230 $output = wpautop($output);
2231 $output = htmlspecialchars($output, ENT_NOQUOTES);
2233 return apply_filters('richedit_pre', $output);
2237 * Formats text for the HTML editor.
2239 * Unless $output is empty it will pass through htmlspecialchars before the
2240 * 'htmledit_pre' filter is applied.
2244 * @param string $output The text to be formatted.
2245 * @return string Formatted text after filter applied.
2247 function wp_htmledit_pre($output) {
2248 if ( !empty($output) )
2249 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2251 return apply_filters('htmledit_pre', $output);
2255 * Perform a deep string replace operation to ensure the values in $search are no longer present
2257 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2258 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2259 * str_replace would return
2264 * @param string|array $search
2265 * @param string $subject
2266 * @return string The processed string
2268 function _deep_replace( $search, $subject ) {
2270 $subject = (string) $subject;
2273 foreach ( (array) $search as $val ) {
2274 while ( strpos( $subject, $val ) !== false ) {
2276 $subject = str_replace( $val, '', $subject );
2285 * Escapes data for use in a MySQL query
2287 * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2290 * @param string $sql Unescaped SQL data
2291 * @return string The cleaned $sql
2293 function esc_sql( $sql ) {
2295 return $wpdb->escape( $sql );
2299 * Checks and cleans a URL.
2301 * A number of characters are removed from the URL. If the URL is for displaying
2302 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
2303 * is applied to the returned cleaned URL.
2306 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2307 * via $protocols or the common ones set in the function.
2309 * @param string $url The URL to be cleaned.
2310 * @param array $protocols Optional. An array of acceptable protocols.
2311 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
2312 * @param string $_context Private. Use esc_url_raw() for database usage.
2313 * @return string The cleaned $url after the 'clean_url' filter is applied.
2315 function esc_url( $url, $protocols = null, $_context = 'display' ) {
2316 $original_url = $url;
2320 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2321 $strip = array('%0d', '%0a', '%0D', '%0A');
2322 $url = _deep_replace($strip, $url);
2323 $url = str_replace(';//', '://', $url);
2324 /* If the URL doesn't appear to contain a scheme, we
2325 * presume it needs http:// appended (unless a relative
2326 * link starting with /, # or ? or a php file).
2328 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
2329 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2330 $url = 'http://' . $url;
2332 // Replace ampersands and single quotes only when displaying.
2333 if ( 'display' == $_context ) {
2334 $url = wp_kses_normalize_entities( $url );
2335 $url = str_replace( '&', '&', $url );
2336 $url = str_replace( "'", ''', $url );
2339 if ( ! is_array( $protocols ) )
2340 $protocols = wp_allowed_protocols();
2341 if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2344 return apply_filters('clean_url', $url, $original_url, $_context);
2348 * Performs esc_url() for database usage.
2353 * @param string $url The URL to be cleaned.
2354 * @param array $protocols An array of acceptable protocols.
2355 * @return string The cleaned URL.
2357 function esc_url_raw( $url, $protocols = null ) {
2358 return esc_url( $url, $protocols, 'db' );
2362 * Convert entities, while preserving already-encoded entities.
2364 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2368 * @param string $myHTML The text to be converted.
2369 * @return string Converted text.
2371 function htmlentities2($myHTML) {
2372 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2373 $translation_table[chr(38)] = '&';
2374 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
2378 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2380 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
2381 * (in a tag attribute, for example onclick="..."). Note that the strings have to
2382 * be in single quotes. The filter 'js_escape' is also applied here.
2386 * @param string $text The text to be escaped.
2387 * @return string Escaped text.
2389 function esc_js( $text ) {
2390 $safe_text = wp_check_invalid_utf8( $text );
2391 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2392 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2393 $safe_text = str_replace( "\r", '', $safe_text );
2394 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2395 return apply_filters( 'js_escape', $safe_text, $text );
2399 * Escaping for HTML blocks.
2403 * @param string $text
2406 function esc_html( $text ) {
2407 $safe_text = wp_check_invalid_utf8( $text );
2408 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2409 return apply_filters( 'esc_html', $safe_text, $text );
2413 * Escaping for HTML attributes.
2417 * @param string $text
2420 function esc_attr( $text ) {
2421 $safe_text = wp_check_invalid_utf8( $text );
2422 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2423 return apply_filters( 'attribute_escape', $safe_text, $text );
2427 * Escaping for textarea values.
2431 * @param string $text
2434 function esc_textarea( $text ) {
2435 $safe_text = htmlspecialchars( $text, ENT_QUOTES );
2436 return apply_filters( 'esc_textarea', $safe_text, $text );
2440 * Escape a HTML tag name.
2444 * @param string $tag_name
2447 function tag_escape($tag_name) {
2448 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
2449 return apply_filters('tag_escape', $safe_tag, $tag_name);
2453 * Escapes text for SQL LIKE special characters % and _.
2457 * @param string $text The text to be escaped.
2458 * @return string text, safe for inclusion in LIKE query.
2460 function like_escape($text) {
2461 return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2465 * Convert full URL paths to absolute paths.
2467 * Removes the http or https protocols and the domain. Keeps the path '/' at the
2468 * beginning, so it isn't a true relative link, but from the web root base.
2472 * @param string $link Full URL path.
2473 * @return string Absolute path.
2475 function wp_make_link_relative( $link ) {
2476 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2480 * Sanitises various option values based on the nature of the option.
2482 * This is basically a switch statement which will pass $value through a number
2483 * of functions depending on the $option.
2487 * @param string $option The name of the option.
2488 * @param string $value The unsanitised value.
2489 * @return string Sanitized value.
2491 function sanitize_option($option, $value) {
2493 switch ( $option ) {
2495 $value = sanitize_email($value);
2496 if ( !is_email($value) ) {
2497 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2498 if ( function_exists('add_settings_error') )
2499 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.'));
2503 case 'new_admin_email':
2504 $value = sanitize_email($value);
2505 if ( !is_email($value) ) {
2506 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2507 if ( function_exists('add_settings_error') )
2508 add_settings_error('new_admin_email', 'invalid_admin_email', __('The email address entered did not appear to be a valid email address. Please enter a valid email address.'));
2512 case 'thumbnail_size_w':
2513 case 'thumbnail_size_h':
2514 case 'medium_size_w':
2515 case 'medium_size_h':
2516 case 'large_size_w':
2517 case 'large_size_h':
2518 case 'embed_size_h':
2519 case 'default_post_edit_rows':
2520 case 'mailserver_port':
2521 case 'comment_max_links':
2522 case 'page_on_front':
2523 case 'page_for_posts':
2524 case 'rss_excerpt_length':
2525 case 'default_category':
2526 case 'default_email_category':
2527 case 'default_link_category':
2528 case 'close_comments_days_old':
2529 case 'comments_per_page':
2530 case 'thread_comments_depth':
2531 case 'users_can_register':
2532 case 'start_of_week':
2533 $value = absint( $value );
2536 case 'embed_size_w':
2537 if ( '' !== $value )
2538 $value = absint( $value );
2541 case 'posts_per_page':
2542 case 'posts_per_rss':
2543 $value = (int) $value;
2544 if ( empty($value) )
2547 $value = abs($value);
2550 case 'default_ping_status':
2551 case 'default_comment_status':
2552 // Options that if not there have 0 value but need to be something like "closed"
2553 if ( $value == '0' || $value == '')
2557 case 'blogdescription':
2559 $value = addslashes($value);
2560 $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2561 $value = stripslashes($value);
2562 $value = esc_html( $value );
2565 case 'blog_charset':
2566 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2571 case 'mailserver_url':
2572 case 'mailserver_login':
2573 case 'mailserver_pass':
2576 $value = strip_tags($value);
2577 $value = addslashes($value);
2578 $value = wp_filter_kses($value); // calls stripslashes then addslashes
2579 $value = stripslashes($value);
2583 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2587 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2588 $value = esc_url_raw($value);
2590 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2591 if ( function_exists('add_settings_error') )
2592 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2597 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2598 $value = esc_url_raw($value);
2600 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2601 if ( function_exists('add_settings_error') )
2602 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2607 $allowed = get_available_languages();
2608 if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
2609 $value = get_option( $option );
2612 case 'timezone_string':
2613 $allowed_zones = timezone_identifiers_list();
2614 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
2615 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2616 if ( function_exists('add_settings_error') )
2617 add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
2621 case 'permalink_structure':
2622 case 'category_base':
2624 $value = esc_url_raw( $value );
2625 $value = str_replace( 'http://', '', $value );
2629 $value = apply_filters("sanitize_option_{$option}", $value, $option);
2635 * Parses a string into variables to be stored in an array.
2637 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2638 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2641 * @uses apply_filters() for the 'wp_parse_str' filter.
2643 * @param string $string The string to be parsed.
2644 * @param array $array Variables will be stored in this array.
2646 function wp_parse_str( $string, &$array ) {
2647 parse_str( $string, $array );
2648 if ( get_magic_quotes_gpc() )
2649 $array = stripslashes_deep( $array );
2650 $array = apply_filters( 'wp_parse_str', $array );
2654 * Convert lone less than signs.
2656 * KSES already converts lone greater than signs.
2658 * @uses wp_pre_kses_less_than_callback in the callback function.
2661 * @param string $text Text to be converted.
2662 * @return string Converted text.
2664 function wp_pre_kses_less_than( $text ) {
2665 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2669 * Callback function used by preg_replace.
2671 * @uses esc_html to format the $matches text.
2674 * @param array $matches Populated by matches to preg_replace.
2675 * @return string The text returned after esc_html if needed.
2677 function wp_pre_kses_less_than_callback( $matches ) {
2678 if ( false === strpos($matches[0], '>') )
2679 return esc_html($matches[0]);
2684 * WordPress implementation of PHP sprintf() with filters.
2687 * @link http://www.php.net/sprintf
2689 * @param string $pattern The string which formatted args are inserted.
2690 * @param mixed $args,... Arguments to be formatted into the $pattern string.
2691 * @return string The formatted string.
2693 function wp_sprintf( $pattern ) {
2694 $args = func_get_args( );
2695 $len = strlen($pattern);
2699 while ( $len > $start ) {
2700 // Last character: append and break
2701 if ( strlen($pattern) - 1 == $start ) {
2702 $result .= substr($pattern, -1);
2706 // Literal %: append and continue
2707 if ( substr($pattern, $start, 2) == '%%' ) {
2713 // Get fragment before next %
2714 $end = strpos($pattern, '%', $start + 1);
2715 if ( false === $end )
2717 $fragment = substr($pattern, $start, $end - $start);
2719 // Fragment has a specifier
2720 if ( $pattern[$start] == '%' ) {
2721 // Find numbered arguments or take the next one in order
2722 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2723 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2724 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2727 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2730 // Apply filters OR sprintf
2731 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2732 if ( $_fragment != $fragment )
2733 $fragment = $_fragment;
2735 $fragment = sprintf($fragment, strval($arg) );
2738 // Append to result and move to next fragment
2739 $result .= $fragment;
2746 * Localize list items before the rest of the content.
2748 * The '%l' must be at the first characters can then contain the rest of the
2749 * content. The list items will have ', ', ', and', and ' and ' added depending
2750 * on the amount of list items in the $args parameter.
2754 * @param string $pattern Content containing '%l' at the beginning.
2755 * @param array $args List items to prepend to the content and replace '%l'.
2756 * @return string Localized list items and rest of the content.
2758 function wp_sprintf_l($pattern, $args) {
2760 if ( substr($pattern, 0, 2) != '%l' )
2763 // Nothing to work with
2767 // Translate and filter the delimiter set (avoid ampersands and entities here)
2768 $l = apply_filters('wp_sprintf_l', array(
2769 /* translators: used between list items, there is a space after the comma */
2770 'between' => __(', '),
2771 /* translators: used between list items, there is a space after the and */
2772 'between_last_two' => __(', and '),
2773 /* translators: used between only two list items, there is a space after the and */
2774 'between_only_two' => __(' and '),
2777 $args = (array) $args;
2778 $result = array_shift($args);
2779 if ( count($args) == 1 )
2780 $result .= $l['between_only_two'] . array_shift($args);
2781 // Loop when more than two args
2784 $arg = array_shift($args);
2787 $result .= $l['between_last_two'] . $arg;
2789 $result .= $l['between'] . $arg;
2791 return $result . substr($pattern, 2);
2795 * Safely extracts not more than the first $count characters from html string.
2797 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2798 * be counted as one character. For example & will be counted as 4, < as
2803 * @param integer $str String to get the excerpt from.
2804 * @param integer $count Maximum number of characters to take.
2805 * @return string The excerpt.
2807 function wp_html_excerpt( $str, $count ) {
2808 $str = wp_strip_all_tags( $str, true );
2809 $str = mb_substr( $str, 0, $count );
2810 // remove part of an entity at the end
2811 $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2816 * Add a Base url to relative links in passed content.
2818 * By default it supports the 'src' and 'href' attributes. However this can be
2819 * changed via the 3rd param.
2823 * @param string $content String to search for links in.
2824 * @param string $base The base URL to prefix to links.
2825 * @param array $attrs The attributes which should be processed.
2826 * @return string The processed content.
2828 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2829 global $_links_add_base;
2830 $_links_add_base = $base;
2831 $attrs = implode('|', (array)$attrs);
2832 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
2836 * Callback to add a base url to relative links in passed content.
2841 * @param string $m The matched link.
2842 * @return string The processed link.
2844 function _links_add_base($m) {
2845 global $_links_add_base;
2846 //1 = attribute name 2 = quotation mark 3 = URL
2847 return $m[1] . '=' . $m[2] .
2848 (strpos($m[3], 'http://') === false ?
2849 path_join($_links_add_base, $m[3]) :
2855 * Adds a Target attribute to all links in passed content.
2857 * This function by default only applies to <a> tags, however this can be
2858 * modified by the 3rd param.
2860 * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
2864 * @param string $content String to search for links in.
2865 * @param string $target The Target to add to the links.
2866 * @param array $tags An array of tags to apply to.
2867 * @return string The processed content.
2869 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2870 global $_links_add_target;
2871 $_links_add_target = $target;
2872 $tags = implode('|', (array)$tags);
2873 return preg_replace_callback( "!<($tags)(.+?)>!i", '_links_add_target', $content );
2877 * Callback to add a target attribute to all links in passed content.
2882 * @param string $m The matched link.
2883 * @return string The processed link.
2885 function _links_add_target( $m ) {
2886 global $_links_add_target;
2888 $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2889 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
2892 // normalize EOL characters and strip duplicate whitespace
2893 function normalize_whitespace( $str ) {
2895 $str = str_replace("\r", "\n", $str);
2896 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
2901 * Properly strip all HTML tags including script and style
2905 * @param string $string String containing HTML tags
2906 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
2907 * @return string The processed string.
2909 function wp_strip_all_tags($string, $remove_breaks = false) {
2910 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
2911 $string = strip_tags($string);
2913 if ( $remove_breaks )
2914 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
2916 return trim($string);
2920 * Sanitize a string from user input or from the db
2922 * check for invalid UTF-8,
2923 * Convert single < characters to entity,
2925 * remove line breaks, tabs and extra white space,
2930 * @param string $str
2933 function sanitize_text_field($str) {
2934 $filtered = wp_check_invalid_utf8( $str );
2936 if ( strpos($filtered, '<') !== false ) {
2937 $filtered = wp_pre_kses_less_than( $filtered );
2938 // This will strip extra whitespace for us.
2939 $filtered = wp_strip_all_tags( $filtered, true );
2941 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
2946 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
2947 $filtered = str_replace($match[0], '', $filtered);
2952 // Strip out the whitespace that may now exist after removing the octets.
2953 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
2956 return apply_filters('sanitize_text_field', $filtered, $str);
2960 * i18n friendly version of basename()
2964 * @param string $path A path.
2965 * @param string $suffix If the filename ends in suffix this will also be cut off.
2968 function wp_basename( $path, $suffix = '' ) {
2969 return urldecode( basename( str_replace( '%2F', '/', urlencode( $path ) ), $suffix ) );
2973 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
2975 * Violating our coding standards for a good function name.
2979 function capital_P_dangit( $text ) {
2980 // Simple replacement for titles
2981 if ( 'the_title' === current_filter() )
2982 return str_replace( 'Wordpress', 'WordPress', $text );
2983 // Still here? Use the more judicious replacement
2984 static $dblq = false;
2985 if ( false === $dblq )
2986 $dblq = _x('“', 'opening curly quote');
2988 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
2989 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
2995 * Sanitize a mime type
2999 * @param string $mime_type Mime type
3000 * @return string Sanitized mime type
3002 function sanitize_mime_type( $mime_type ) {
3003 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3004 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );