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_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
32 $default_no_texturize_tags, $default_no_texturize_shortcodes;
34 // No need to set up these static variables more than once
35 if ( ! isset( $static_characters ) ) {
36 /* translators: opening curly double quote */
37 $opening_quote = _x( '“', 'opening curly double quote' );
38 /* translators: closing curly double quote */
39 $closing_quote = _x( '”', 'closing curly double quote' );
41 /* translators: apostrophe, for example in 'cause or can't */
42 $apos = _x( '’', 'apostrophe' );
44 /* translators: prime, for example in 9' (nine feet) */
45 $prime = _x( '′', 'prime' );
46 /* translators: double prime, for example in 9" (nine inches) */
47 $double_prime = _x( '″', 'double prime' );
49 /* translators: opening curly single quote */
50 $opening_single_quote = _x( '‘', 'opening curly single quote' );
51 /* translators: closing curly single quote */
52 $closing_single_quote = _x( '’', 'closing curly single quote' );
54 /* translators: en dash */
55 $en_dash = _x( '–', 'en dash' );
56 /* translators: em dash */
57 $em_dash = _x( '—', 'em dash' );
59 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
60 $default_no_texturize_shortcodes = array('code');
62 // if a plugin has provided an autocorrect array, use it
63 if ( isset($wp_cockneyreplace) ) {
64 $cockney = array_keys($wp_cockneyreplace);
65 $cockneyreplace = array_values($wp_cockneyreplace);
66 } elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
67 $cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
68 $cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
70 $cockney = $cockneyreplace = array();
73 $static_characters = array_merge( array( '---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)' ), $cockney );
74 $static_replacements = array_merge( array( $em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '…', $opening_quote, $closing_quote, ' ™' ), $cockneyreplace );
77 * Regex for common whitespace characters.
79 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
80 * This is designed to replace the PCRE \s sequence. In #WP22692, that sequence
81 * was found to be unreliable due to random inclusion of the A0 byte.
83 $spaces = '[\r\n\t ]|\xC2\xA0| ';
86 // Pattern-based replacements of characters.
89 // '99 '99s '99's (apostrophe)
90 if ( "'" !== $apos ) {
91 $dynamic[ '/\'(?=\d)/' ] = $apos;
94 // Single quote at start, or preceded by (, {, <, [, ", or spaces.
95 if ( "'" !== $opening_single_quote ) {
96 $dynamic[ '/(?<=\A|[([{<"]|' . $spaces . ')\'/' ] = $opening_single_quote;
100 if ( '"' !== $double_prime ) {
101 $dynamic[ '/(?<=\d)"/' ] = $double_prime;
105 if ( "'" !== $prime ) {
106 $dynamic[ '/(?<=\d)\'/' ] = $prime;
109 // Apostrophe in a word. No spaces or double primes.
110 if ( "'" !== $apos ) {
111 $dynamic[ '/(?<!' . $spaces . ')\'(?!\'|' . $spaces . ')/' ] = $apos;
114 // Double quote at start, or preceded by (, {, <, [, or spaces, and not followed by spaces.
115 if ( '"' !== $opening_quote ) {
116 $dynamic[ '/(?<=\A|[([{<]|' . $spaces . ')"(?!' . $spaces . ')/' ] = $opening_quote;
119 // Any remaining double quotes.
120 if ( '"' !== $closing_quote ) {
121 $dynamic[ '/"/' ] = $closing_quote;
124 // Single quotes followed by spaces or a period.
125 if ( "'" !== $closing_single_quote ) {
126 $dynamic[ '/\'(?=\Z|\.|' . $spaces . ')/' ] = $closing_single_quote;
129 $dynamic_characters = array_keys( $dynamic );
130 $dynamic_replacements = array_values( $dynamic );
133 // Transform into regexp sub-expression used in _wptexturize_pushpop_element
134 // Must do this every time in case plugins use these filters in a context sensitive manner
136 * Filter the list of HTML elements not to texturize.
140 * @param array $default_no_texturize_tags An array of HTML element names.
142 $no_texturize_tags = '(' . implode( '|', apply_filters( 'no_texturize_tags', $default_no_texturize_tags ) ) . ')';
144 * Filter the list of shortcodes not to texturize.
148 * @param array $default_no_texturize_shortcodes An array of shortcode names.
150 $no_texturize_shortcodes = '(' . implode( '|', apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes ) ) . ')';
152 $no_texturize_tags_stack = array();
153 $no_texturize_shortcodes_stack = array();
155 $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
157 foreach ( $textarr as &$curl ) {
158 if ( empty( $curl ) ) {
162 // Only call _wptexturize_pushpop_element if first char is correct tag opening
164 if ( '<' === $first ) {
165 _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
166 } elseif ( '[' === $first ) {
167 _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
168 } elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
170 // This is not a tag, nor is the texturization disabled static strings
171 $curl = str_replace($static_characters, $static_replacements, $curl);
173 // regular expressions
174 $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
177 if ( 1 === preg_match( '/(?<=\d)x\d/', $text ) ) {
178 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
179 $curl = preg_replace( '/\b(\d+)x(\d+)\b/', '$1×$2', $curl );
183 // Replace each & with & unless it already looks like an entity.
184 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
186 return implode( '', $textarr );
190 * Search for disabled element tags. Push element to stack on tag open and pop
191 * on tag close. Assumes first character of $text is tag opening.
196 * @param string $text Text to check. First character is assumed to be $opening
197 * @param array $stack Array used as stack of opened tag elements
198 * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
199 * @param string $opening Tag opening character, assumed to be 1 character long
200 * @param string $closing Tag closing character
202 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
203 // Check if it is a closing tag -- otherwise assume opening tag
204 if (strncmp($opening . '/', $text, 2)) {
205 // Opening? Check $text+1 against disabled elements
206 if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
208 * This disables texturize until we find a closing tag of our type
209 * (e.g. <pre>) even if there was invalid nesting before that
211 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
212 * "baba" won't be texturize
215 array_push($stack, $matches[1]);
218 // Closing? Check $text+2 against disabled elements
219 $c = preg_quote($closing, '/');
220 if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
221 $last = array_pop($stack);
223 // Make sure it matches the opening tag
224 if ( $last != $matches[1] ) {
225 array_push( $stack, $last );
232 * Replaces double line-breaks with paragraph elements.
234 * A group of regex replaces used to identify text formatted with newlines and
235 * replace double line-breaks with HTML paragraph tags. The remaining
236 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
241 * @param string $pee The text which has to be formatted.
242 * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
243 * @return string Text which has been converted into correct paragraph tags.
245 function wpautop($pee, $br = true) {
248 if ( trim($pee) === '' )
251 $pee = $pee . "\n"; // just to make things a little easier, pad the end
253 if ( strpos($pee, '<pre') !== false ) {
254 $pee_parts = explode( '</pre>', $pee );
255 $last_pee = array_pop($pee_parts);
259 foreach ( $pee_parts as $pee_part ) {
260 $start = strpos($pee_part, '<pre');
263 if ( $start === false ) {
268 $name = "<pre wp-pre-tag-$i></pre>";
269 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
271 $pee .= substr( $pee_part, 0, $start ) . $name;
278 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
279 // Space things out a little
280 $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section|article|aside|hgroup|header|footer|nav|figure|details|menu|summary)';
281 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
282 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
283 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
285 if ( strpos( $pee, '</object>' ) !== false ) {
286 // no P/BR around param and embed
287 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
288 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
289 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
292 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
293 // no P/BR around source and track
294 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
295 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
296 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
299 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
300 // make paragraphs, including one at the end
301 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
304 foreach ( $pees as $tinkle ) {
305 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
308 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
309 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
310 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
311 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
312 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
313 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
314 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
315 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
318 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
319 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
320 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
323 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
324 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
325 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
327 if ( !empty($pre_tags) )
328 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
334 * Newline preservation help function for wpautop
339 * @param array $matches preg_replace_callback matches array
342 function _autop_newline_preservation_helper( $matches ) {
343 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
347 * Don't auto-p wrap shortcodes that stand alone
349 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
353 * @param string $pee The content.
354 * @return string The filtered content.
356 function shortcode_unautop( $pee ) {
357 global $shortcode_tags;
359 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
363 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
367 . '<p>' // Opening paragraph
368 . '\\s*+' // Optional leading whitespace
369 . '(' // 1: The shortcode
370 . '\\[' // Opening bracket
371 . "($tagregexp)" // 2: Shortcode name
372 . '(?![\\w-])' // Not followed by word character or hyphen
373 // Unroll the loop: Inside the opening shortcode tag
374 . '[^\\]\\/]*' // Not a closing bracket or forward slash
376 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
377 . '[^\\]\\/]*' // Not a closing bracket or forward slash
380 . '\\/\\]' // Self closing tag and closing bracket
382 . '\\]' // Closing bracket
383 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
384 . '[^\\[]*+' // Not an opening bracket
386 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
387 . '[^\\[]*+' // Not an opening bracket
389 . '\\[\\/\\2\\]' // Closing shortcode tag
393 . '\\s*+' // optional trailing whitespace
394 . '<\\/p>' // closing paragraph
397 return preg_replace( $pattern, '$1', $pee );
401 * Checks to see if a string is utf8 encoded.
403 * NOTE: This function checks for 5-Byte sequences, UTF8
404 * has Bytes Sequences with a maximum length of 4.
406 * @author bmorel at ssi dot fr (modified)
409 * @param string $str The string to be checked
410 * @return bool True if $str fits a UTF-8 model, false otherwise.
412 function seems_utf8($str) {
413 $length = strlen($str);
414 for ($i=0; $i < $length; $i++) {
416 if ($c < 0x80) $n = 0; # 0bbbbbbb
417 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
418 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
419 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
420 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
421 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
422 else return false; # Does not match any model
423 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
424 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
432 * Converts a number of special characters into their HTML entities.
434 * Specifically deals with: &, <, >, ", and '.
436 * $quote_style can be set to ENT_COMPAT to encode " to
437 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
442 * @param string $string The text which is to be encoded.
443 * @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.
444 * @param string $charset Optional. The character encoding of the string. Default is false.
445 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
446 * @return string The encoded text with HTML entities.
448 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
449 $string = (string) $string;
451 if ( 0 === strlen( $string ) )
454 // Don't bother if there are no specialchars - saves some processing
455 if ( ! preg_match( '/[&<>"\']/', $string ) )
458 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
459 if ( empty( $quote_style ) )
460 $quote_style = ENT_NOQUOTES;
461 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
462 $quote_style = ENT_QUOTES;
464 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
467 if ( ! isset( $_charset ) ) {
468 $alloptions = wp_load_alloptions();
469 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
471 $charset = $_charset;
474 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
477 $_quote_style = $quote_style;
479 if ( $quote_style === 'double' ) {
480 $quote_style = ENT_COMPAT;
481 $_quote_style = ENT_COMPAT;
482 } elseif ( $quote_style === 'single' ) {
483 $quote_style = ENT_NOQUOTES;
486 // Handle double encoding ourselves
487 if ( $double_encode ) {
488 $string = @htmlspecialchars( $string, $quote_style, $charset );
490 // Decode & into &
491 $string = wp_specialchars_decode( $string, $_quote_style );
493 // Guarantee every &entity; is valid or re-encode the &
494 $string = wp_kses_normalize_entities( $string );
496 // Now re-encode everything except &entity;
497 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
499 for ( $i = 0; $i < count( $string ); $i += 2 )
500 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
502 $string = implode( '', $string );
505 // Backwards compatibility
506 if ( 'single' === $_quote_style )
507 $string = str_replace( "'", ''', $string );
513 * Converts a number of HTML entities into their special characters.
515 * Specifically deals with: &, <, >, ", and '.
517 * $quote_style can be set to ENT_COMPAT to decode " entities,
518 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
522 * @param string $string The text which is to be decoded.
523 * @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.
524 * @return string The decoded text without HTML entities.
526 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
527 $string = (string) $string;
529 if ( 0 === strlen( $string ) ) {
533 // Don't bother if there are no entities - saves a lot of processing
534 if ( strpos( $string, '&' ) === false ) {
538 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
539 if ( empty( $quote_style ) ) {
540 $quote_style = ENT_NOQUOTES;
541 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
542 $quote_style = ENT_QUOTES;
545 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
546 $single = array( ''' => '\'', ''' => '\'' );
547 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
548 $double = array( '"' => '"', '"' => '"', '"' => '"' );
549 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
550 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
551 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
553 if ( $quote_style === ENT_QUOTES ) {
554 $translation = array_merge( $single, $double, $others );
555 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
556 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
557 $translation = array_merge( $double, $others );
558 $translation_preg = array_merge( $double_preg, $others_preg );
559 } elseif ( $quote_style === 'single' ) {
560 $translation = array_merge( $single, $others );
561 $translation_preg = array_merge( $single_preg, $others_preg );
562 } elseif ( $quote_style === ENT_NOQUOTES ) {
563 $translation = $others;
564 $translation_preg = $others_preg;
567 // Remove zero padding on numeric entities
568 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
570 // Replace characters according to translation table
571 return strtr( $string, $translation );
575 * Checks for invalid UTF8 in a string.
579 * @param string $string The text which is to be checked.
580 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
581 * @return string The checked text.
583 function wp_check_invalid_utf8( $string, $strip = false ) {
584 $string = (string) $string;
586 if ( 0 === strlen( $string ) ) {
590 // Store the site charset as a static to avoid multiple calls to get_option()
592 if ( !isset( $is_utf8 ) ) {
593 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
599 // Check for support for utf8 in the installed PCRE library once and store the result in a static
601 if ( !isset( $utf8_pcre ) ) {
602 $utf8_pcre = @preg_match( '/^./u', 'a' );
604 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
609 // preg_match fails when it encounters invalid UTF8 in $string
610 if ( 1 === @preg_match( '/^./us', $string ) ) {
614 // Attempt to strip the bad chars if requested (not recommended)
615 if ( $strip && function_exists( 'iconv' ) ) {
616 return iconv( 'utf-8', 'utf-8', $string );
623 * Encode the Unicode values to be used in the URI.
627 * @param string $utf8_string
628 * @param int $length Max length of the string
629 * @return string String with Unicode encoded for URI.
631 function utf8_uri_encode( $utf8_string, $length = 0 ) {
637 $string_length = strlen( $utf8_string );
638 for ($i = 0; $i < $string_length; $i++ ) {
640 $value = ord( $utf8_string[ $i ] );
642 if ( $value < 128 ) {
643 if ( $length && ( $unicode_length >= $length ) )
645 $unicode .= chr($value);
648 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
652 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
654 if ( count( $values ) == $num_octets ) {
655 if ($num_octets == 3) {
656 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
657 $unicode_length += 9;
659 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
660 $unicode_length += 6;
673 * Converts all accent characters to ASCII characters.
675 * If there are no accent characters, then the string given is just returned.
679 * @param string $string Text that might have accent characters
680 * @return string Filtered string with replaced "nice" characters.
682 function remove_accents($string) {
683 if ( !preg_match('/[\x80-\xff]/', $string) )
686 if (seems_utf8($string)) {
688 // Decompositions for Latin-1 Supplement
689 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
690 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
691 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
692 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
693 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
694 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
695 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
696 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
697 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
698 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
699 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
700 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
701 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
702 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
703 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
704 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
705 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
706 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
707 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
708 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
709 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
710 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
711 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
712 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
713 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
714 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
715 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
716 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
717 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
718 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
719 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
720 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
721 // Decompositions for Latin Extended-A
722 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
723 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
724 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
725 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
726 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
727 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
728 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
729 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
730 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
731 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
732 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
733 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
734 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
735 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
736 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
737 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
738 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
739 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
740 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
741 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
742 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
743 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
744 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
745 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
746 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
747 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
748 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
749 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
750 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
751 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
752 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
753 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
754 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
755 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
756 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
757 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
758 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
759 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
760 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
761 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
762 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
763 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
764 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
765 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
766 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
767 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
768 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
769 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
770 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
771 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
772 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
773 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
774 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
775 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
776 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
777 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
778 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
779 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
780 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
781 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
782 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
783 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
784 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
785 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
786 // Decompositions for Latin Extended-B
787 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
788 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
790 chr(226).chr(130).chr(172) => 'E',
792 chr(194).chr(163) => '',
793 // Vowels with diacritic (Vietnamese)
795 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
796 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
798 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
799 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
800 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
801 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
802 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
803 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
804 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
806 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
807 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
808 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
809 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
810 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
811 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
812 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
813 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
814 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
815 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
816 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
817 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
819 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
820 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
821 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
822 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
823 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
824 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
825 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
826 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
828 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
829 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
830 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
831 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
832 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
833 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
835 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
836 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
837 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
838 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
839 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
840 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
841 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
842 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
843 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
844 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
845 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
846 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
847 // Vowels with diacritic (Chinese, Hanyu Pinyin)
848 chr(201).chr(145) => 'a',
850 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
852 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
854 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
855 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
856 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
857 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
858 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
860 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
863 // Used for locale-specific rules
864 $locale = get_locale();
866 if ( 'de_DE' == $locale ) {
867 $chars[ chr(195).chr(132) ] = 'Ae';
868 $chars[ chr(195).chr(164) ] = 'ae';
869 $chars[ chr(195).chr(150) ] = 'Oe';
870 $chars[ chr(195).chr(182) ] = 'oe';
871 $chars[ chr(195).chr(156) ] = 'Ue';
872 $chars[ chr(195).chr(188) ] = 'ue';
873 $chars[ chr(195).chr(159) ] = 'ss';
874 } elseif ( 'da_DK' === $locale ) {
875 $chars[ chr(195).chr(134) ] = 'Ae';
876 $chars[ chr(195).chr(166) ] = 'ae';
877 $chars[ chr(195).chr(152) ] = 'Oe';
878 $chars[ chr(195).chr(184) ] = 'oe';
879 $chars[ chr(195).chr(133) ] = 'Aa';
880 $chars[ chr(195).chr(165) ] = 'aa';
883 $string = strtr($string, $chars);
885 // Assume ISO-8859-1 if not UTF-8
886 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
887 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
888 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
889 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
890 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
891 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
892 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
893 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
894 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
895 .chr(252).chr(253).chr(255);
897 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
899 $string = strtr($string, $chars['in'], $chars['out']);
900 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
901 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
902 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
909 * Sanitizes a filename, replacing whitespace with dashes.
911 * Removes special characters that are illegal in filenames on certain
912 * operating systems and special characters requiring special escaping
913 * to manipulate at the command line. Replaces spaces and consecutive
914 * dashes with a single dash. Trims period, dash and underscore from beginning
915 * and end of filename.
919 * @param string $filename The filename to be sanitized
920 * @return string The sanitized filename
922 function sanitize_file_name( $filename ) {
923 $filename_raw = $filename;
924 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
926 * Filter the list of characters to remove from a filename.
930 * @param array $special_chars Characters to remove.
931 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
933 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
934 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
935 $filename = str_replace($special_chars, '', $filename);
936 $filename = preg_replace('/[\s-]+/', '-', $filename);
937 $filename = trim($filename, '.-_');
939 // Split the filename into a base and extension[s]
940 $parts = explode('.', $filename);
942 // Return if only one extension
943 if ( count( $parts ) <= 2 ) {
945 * Filter a sanitized filename string.
949 * @param string $filename Sanitized filename.
950 * @param string $filename_raw The filename prior to sanitization.
952 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
955 // Process multiple extensions
956 $filename = array_shift($parts);
957 $extension = array_pop($parts);
958 $mimes = get_allowed_mime_types();
961 * Loop over any intermediate extensions. Postfix them with a trailing underscore
962 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
964 foreach ( (array) $parts as $part) {
965 $filename .= '.' . $part;
967 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
969 foreach ( $mimes as $ext_preg => $mime_match ) {
970 $ext_preg = '!^(' . $ext_preg . ')$!i';
971 if ( preg_match( $ext_preg, $part ) ) {
980 $filename .= '.' . $extension;
981 /** This filter is documented in wp-includes/formatting.php */
982 return apply_filters('sanitize_file_name', $filename, $filename_raw);
986 * Sanitizes a username, stripping out unsafe characters.
988 * Removes tags, octets, entities, and if strict is enabled, will only keep
989 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
990 * raw username (the username in the parameter), and the value of $strict as
991 * parameters for the 'sanitize_user' filter.
995 * @param string $username The username to be sanitized.
996 * @param bool $strict If set limits $username to specific characters. Default false.
997 * @return string The sanitized username, after passing through filters.
999 function sanitize_user( $username, $strict = false ) {
1000 $raw_username = $username;
1001 $username = wp_strip_all_tags( $username );
1002 $username = remove_accents( $username );
1004 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1005 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1007 // If strict, reduce to ASCII for max portability.
1009 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1011 $username = trim( $username );
1012 // Consolidate contiguous whitespace
1013 $username = preg_replace( '|\s+|', ' ', $username );
1016 * Filter a sanitized username string.
1020 * @param string $username Sanitized username.
1021 * @param string $raw_username The username prior to sanitization.
1022 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1024 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1028 * Sanitizes a string key.
1030 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1034 * @param string $key String key
1035 * @return string Sanitized key
1037 function sanitize_key( $key ) {
1039 $key = strtolower( $key );
1040 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1043 * Filter a sanitized key string.
1047 * @param string $key Sanitized key.
1048 * @param string $raw_key The key prior to sanitization.
1050 return apply_filters( 'sanitize_key', $key, $raw_key );
1054 * Sanitizes a title, or returns a fallback title.
1056 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1057 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1062 * @param string $title The string to be sanitized.
1063 * @param string $fallback_title Optional. A title to use if $title is empty.
1064 * @param string $context Optional. The operation for which the string is sanitized
1065 * @return string The sanitized string.
1067 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1068 $raw_title = $title;
1070 if ( 'save' == $context )
1071 $title = remove_accents($title);
1074 * Filter a sanitized title string.
1078 * @param string $title Sanitized title.
1079 * @param string $raw_title The title prior to sanitization.
1080 * @param string $context The context for which the title is being sanitized.
1082 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1084 if ( '' === $title || false === $title )
1085 $title = $fallback_title;
1091 * Sanitizes a title with the 'query' context.
1093 * Used for querying the database for a value from URL.
1096 * @uses sanitize_title()
1098 * @param string $title The string to be sanitized.
1099 * @return string The sanitized string.
1101 function sanitize_title_for_query( $title ) {
1102 return sanitize_title( $title, '', 'query' );
1106 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1108 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1109 * Whitespace becomes a dash.
1113 * @param string $title The title to be sanitized.
1114 * @param string $raw_title Optional. Not used.
1115 * @param string $context Optional. The operation for which the string is sanitized.
1116 * @return string The sanitized title.
1118 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1119 $title = strip_tags($title);
1120 // Preserve escaped octets.
1121 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1122 // Remove percent signs that are not part of an octet.
1123 $title = str_replace('%', '', $title);
1125 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1127 if (seems_utf8($title)) {
1128 if (function_exists('mb_strtolower')) {
1129 $title = mb_strtolower($title, 'UTF-8');
1131 $title = utf8_uri_encode($title, 200);
1134 $title = strtolower($title);
1135 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1136 $title = str_replace('.', '-', $title);
1138 if ( 'save' == $context ) {
1139 // Convert nbsp, ndash and mdash to hyphens
1140 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1142 // Strip these characters entirely
1143 $title = str_replace( array(
1147 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1149 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1150 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1151 // copy, reg, deg, hellip and trade
1152 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1154 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1155 // grave accent, macron, caron
1156 '%cc%80', '%cc%84', '%cc%8c',
1159 // Convert times to x
1160 $title = str_replace( '%c3%97', 'x', $title );
1163 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1164 $title = preg_replace('/\s+/', '-', $title);
1165 $title = preg_replace('|-+|', '-', $title);
1166 $title = trim($title, '-');
1172 * Ensures a string is a valid SQL order by clause.
1174 * Accepts one or more columns, with or without ASC/DESC, and also accepts
1179 * @param string $orderby Order by string to be checked.
1180 * @return string|bool Returns the order by clause if it is a match, false otherwise.
1182 function sanitize_sql_orderby( $orderby ){
1183 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
1190 * Sanitizes an HTML classname to ensure it only contains valid characters.
1192 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1193 * string then it will return the alternative value supplied.
1195 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1199 * @param string $class The classname to be sanitized
1200 * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
1201 * Defaults to an empty string.
1202 * @return string The sanitized value
1204 function sanitize_html_class( $class, $fallback = '' ) {
1205 //Strip out any % encoded octets
1206 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1208 //Limit to A-Z,a-z,0-9,_,-
1209 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1211 if ( '' == $sanitized )
1212 $sanitized = $fallback;
1215 * Filter a sanitized HTML class string.
1219 * @param string $sanitized The sanitized HTML class.
1220 * @param string $class HTML class before sanitization.
1221 * @param string $fallback The fallback string.
1223 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1227 * Converts a number of characters from a string.
1229 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
1230 * converted into correct XHTML and Unicode characters are converted to the
1235 * @param string $content String of characters to be converted.
1236 * @param string $deprecated Not used.
1237 * @return string Converted string.
1239 function convert_chars($content, $deprecated = '') {
1240 if ( !empty( $deprecated ) )
1241 _deprecated_argument( __FUNCTION__, '0.71' );
1243 // Translation of invalid Unicode references range to valid range
1244 $wp_htmltranswinuni = array(
1245 '€' => '€', // the Euro sign
1247 '‚' => '‚', // these are Windows CP1252 specific characters
1248 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1249 '„' => '„',
1250 '…' => '…',
1251 '†' => '†',
1252 '‡' => '‡',
1253 'ˆ' => 'ˆ',
1254 '‰' => '‰',
1255 'Š' => 'Š',
1256 '‹' => '‹',
1257 'Œ' => 'Œ',
1259 'Ž' => 'Ž',
1262 '‘' => '‘',
1263 '’' => '’',
1264 '“' => '“',
1265 '”' => '”',
1266 '•' => '•',
1267 '–' => '–',
1268 '—' => '—',
1269 '˜' => '˜',
1270 '™' => '™',
1271 'š' => 'š',
1272 '›' => '›',
1273 'œ' => 'œ',
1275 'ž' => 'ž',
1276 'Ÿ' => 'Ÿ'
1279 // Remove metadata tags
1280 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1281 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1283 // Converts lone & characters into & (a.k.a. &)
1284 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1287 $content = strtr($content, $wp_htmltranswinuni);
1289 // Just a little XHTML help
1290 $content = str_replace('<br>', '<br />', $content);
1291 $content = str_replace('<hr>', '<hr />', $content);
1297 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1301 * @param string $text Text to be balanced
1302 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1303 * @return string Balanced text
1305 function balanceTags( $text, $force = false ) {
1306 if ( $force || get_option('use_balanceTags') == 1 ) {
1307 return force_balance_tags( $text );
1314 * Balances tags of string using a modified stack.
1318 * @author Leonard Lin <leonard@acm.org>
1320 * @copyright November 4, 2001
1322 * @todo Make better - change loop condition to $text in 1.2
1323 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1324 * 1.1 Fixed handling of append/stack pop order of end text
1325 * Added Cleaning Hooks
1328 * @param string $text Text to be balanced.
1329 * @return string Balanced text.
1331 function force_balance_tags( $text ) {
1332 $tagstack = array();
1336 // Known single-entity/self-closing tags
1337 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1338 // Tags that can be immediately nested within themselves
1339 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1341 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1342 $text = str_replace('< !--', '< !--', $text);
1343 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1344 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1346 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1347 $newtext .= $tagqueue;
1349 $i = strpos($text, $regex[0]);
1350 $l = strlen($regex[0]);
1352 // clear the shifter
1355 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1356 $tag = strtolower(substr($regex[1],1));
1357 // if too many closing tags
1358 if( $stacksize <= 0 ) {
1360 // or close to be safe $tag = '/' . $tag;
1362 // if stacktop value = tag close value then pop
1363 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1364 $tag = '</' . $tag . '>'; // Close Tag
1366 array_pop( $tagstack );
1368 } else { // closing tag not at top, search for it
1369 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1370 if ( $tagstack[$j] == $tag ) {
1371 // add tag to tagqueue
1372 for ( $k = $stacksize-1; $k >= $j; $k--) {
1373 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1381 } else { // Begin Tag
1382 $tag = strtolower($regex[1]);
1386 // If it's an empty tag "< >", do nothing
1390 // ElseIf it presents itself as a self-closing tag...
1391 elseif ( substr( $regex[2], -1 ) == '/' ) {
1392 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1393 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1394 if ( ! in_array( $tag, $single_tags ) )
1395 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1397 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1398 elseif ( in_array($tag, $single_tags) ) {
1401 // Else it's not a single-entity tag
1403 // If the top of the stack is the same as the tag we want to push, close previous tag
1404 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1405 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1408 $stacksize = array_push( $tagstack, $tag );
1412 $attributes = $regex[2];
1413 if( ! empty( $attributes ) && $attributes[0] != '>' )
1414 $attributes = ' ' . $attributes;
1416 $tag = '<' . $tag . $attributes . '>';
1417 //If already queuing a close tag, then put this tag on, too
1418 if ( !empty($tagqueue) ) {
1423 $newtext .= substr($text, 0, $i) . $tag;
1424 $text = substr($text, $i + $l);
1428 $newtext .= $tagqueue;
1430 // Add Remaining text
1434 while( $x = array_pop($tagstack) )
1435 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1437 // WP fix for the bug with HTML comments
1438 $newtext = str_replace("< !--","<!--",$newtext);
1439 $newtext = str_replace("< !--","< !--",$newtext);
1445 * Acts on text which is about to be edited.
1447 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1448 * to convert special characters to HTML entities. If $richedit is set to true,
1449 * it is simply a holder for the 'format_to_edit' filter.
1453 * @param string $content The text about to be edited.
1454 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1455 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1457 function format_to_edit( $content, $richedit = false ) {
1459 * Filter the text to be formatted for editing.
1463 * @param string $content The text, prior to formatting for editing.
1465 $content = apply_filters( 'format_to_edit', $content );
1467 $content = esc_textarea( $content );
1472 * Add leading zeros when necessary.
1474 * If you set the threshold to '4' and the number is '10', then you will get
1475 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1476 * will get back '5000'.
1478 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1479 * and the size of the number. If the number is large enough, then no zeros will
1484 * @param mixed $number Number to append zeros to if not greater than threshold.
1485 * @param int $threshold Digit places number needs to be to not have zeros added.
1486 * @return string Adds leading zeros to number if needed.
1488 function zeroise($number, $threshold) {
1489 return sprintf('%0'.$threshold.'s', $number);
1493 * Adds backslashes before letters and before a number at the start of a string.
1497 * @param string $string Value to which backslashes will be added.
1498 * @return string String with backslashes inserted.
1500 function backslashit($string) {
1501 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1502 $string = '\\\\' . $string;
1503 return addcslashes( $string, 'A..Za..z' );
1507 * Appends a trailing slash.
1509 * Will remove trailing forward and backslashes if it exists already before adding
1510 * a trailing forward slash. This prevents double slashing a string or path.
1512 * The primary use of this is for paths and thus should be used for paths. It is
1513 * not restricted to paths and offers no specific path support.
1517 * @param string $string What to add the trailing slash to.
1518 * @return string String with trailing slash added.
1520 function trailingslashit( $string ) {
1521 return untrailingslashit( $string ) . '/';
1525 * Removes trailing forward slashes and backslashes if they exist.
1527 * The primary use of this is for paths and thus should be used for paths. It is
1528 * not restricted to paths and offers no specific path support.
1532 * @param string $string What to remove the trailing slashes from.
1533 * @return string String without the trailing slashes.
1535 function untrailingslashit( $string ) {
1536 return rtrim( $string, '/\\' );
1540 * Adds slashes to escape strings.
1542 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1543 * http://www.php.net/magic_quotes} for more details.
1547 * @param string $gpc The string returned from HTTP request data.
1548 * @return string Returns a string escaped with slashes.
1550 function addslashes_gpc($gpc) {
1551 if ( get_magic_quotes_gpc() )
1552 $gpc = stripslashes($gpc);
1554 return wp_slash($gpc);
1558 * Navigates through an array and removes slashes from the values.
1560 * If an array is passed, the array_map() function causes a callback to pass the
1561 * value back to the function. The slashes from this value will removed.
1565 * @param mixed $value The value to be stripped.
1566 * @return mixed Stripped value.
1568 function stripslashes_deep($value) {
1569 if ( is_array($value) ) {
1570 $value = array_map('stripslashes_deep', $value);
1571 } elseif ( is_object($value) ) {
1572 $vars = get_object_vars( $value );
1573 foreach ($vars as $key=>$data) {
1574 $value->{$key} = stripslashes_deep( $data );
1576 } elseif ( is_string( $value ) ) {
1577 $value = stripslashes($value);
1584 * Navigates through an array and encodes the values to be used in a URL.
1589 * @param array|string $value The array or string to be encoded.
1590 * @return array|string $value The encoded array (or string from the callback).
1592 function urlencode_deep($value) {
1593 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1598 * Navigates through an array and raw encodes the values to be used in a URL.
1602 * @param array|string $value The array or string to be encoded.
1603 * @return array|string $value The encoded array (or string from the callback).
1605 function rawurlencode_deep( $value ) {
1606 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1610 * Converts email addresses characters to HTML entities to block spam bots.
1614 * @param string $email_address Email address.
1615 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
1616 * @return string Converted email address.
1618 function antispambot( $email_address, $hex_encoding = 0 ) {
1619 $email_no_spam_address = '';
1620 for ( $i = 0; $i < strlen( $email_address ); $i++ ) {
1621 $j = rand( 0, 1 + $hex_encoding );
1623 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
1624 } elseif ( $j == 1 ) {
1625 $email_no_spam_address .= $email_address[$i];
1626 } elseif ( $j == 2 ) {
1627 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
1631 $email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
1633 return $email_no_spam_address;
1637 * Callback to convert URI match to HTML A element.
1639 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1640 * make_clickable()}.
1645 * @param array $matches Single Regex Match.
1646 * @return string HTML A element with URI address.
1648 function _make_url_clickable_cb($matches) {
1651 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1652 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1653 // Then we can let the parenthesis balancer do its thing below.
1654 $url .= $matches[3];
1657 $suffix = $matches[3];
1660 // Include parentheses in the URL only if paired
1661 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1662 $suffix = strrchr( $url, ')' ) . $suffix;
1663 $url = substr( $url, 0, strrpos( $url, ')' ) );
1666 $url = esc_url($url);
1670 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1674 * Callback to convert URL match to HTML A element.
1676 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1677 * make_clickable()}.
1682 * @param array $matches Single Regex Match.
1683 * @return string HTML A element with URL address.
1685 function _make_web_ftp_clickable_cb($matches) {
1687 $dest = $matches[2];
1688 $dest = 'http://' . $dest;
1689 $dest = esc_url($dest);
1693 // removed trailing [.,;:)] from URL
1694 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1695 $ret = substr($dest, -1);
1696 $dest = substr($dest, 0, strlen($dest)-1);
1698 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1702 * Callback to convert email address match to HTML A element.
1704 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1705 * make_clickable()}.
1710 * @param array $matches Single Regex Match.
1711 * @return string HTML A element with email address.
1713 function _make_email_clickable_cb($matches) {
1714 $email = $matches[2] . '@' . $matches[3];
1715 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1719 * Convert plaintext URI to HTML links.
1721 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1726 * @param string $text Content to convert URIs.
1727 * @return string Content with converted URIs.
1729 function make_clickable( $text ) {
1731 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
1732 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
1733 foreach ( $textarr as $piece ) {
1735 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
1737 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
1740 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
1745 // Long strings might contain expensive edge cases ...
1746 if ( 10000 < strlen( $piece ) ) {
1748 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
1749 if ( 2101 < strlen( $chunk ) ) {
1750 $r .= $chunk; // Too big, no whitespace: bail.
1752 $r .= make_clickable( $chunk );
1756 $ret = " $piece "; // Pad with whitespace to simplify the regexes
1759 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
1761 [\\w]{1,20}+:// # Scheme and hier-part prefix
1762 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
1763 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
1764 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
1765 [\'.,;:!?)] # Punctuation URL character
1766 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
1769 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
1770 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
1771 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
1773 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
1775 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
1776 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
1778 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
1783 // Cleanup of accidental links within links
1784 $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
1789 * Breaks a string into chunks by splitting at whitespace characters.
1790 * The length of each returned chunk is as close to the specified length goal as possible,
1791 * with the caveat that each chunk includes its trailing delimiter.
1792 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
1794 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
1796 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
1799 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
1801 * 0 => '1234 67890 ', // 11 characters: Perfect split
1802 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
1803 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
1804 * 3 => '1234 890 ', // 11 characters: Perfect split
1805 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
1806 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
1807 * 6 => ' 45678 ', // 11 characters: Perfect split
1808 * 7 => '1 3 5 7 9', // 9 characters: End of $string
1815 * @param string $string The string to split.
1816 * @param int $goal The desired chunk length.
1817 * @return array Numeric array of chunks.
1819 function _split_str_by_whitespace( $string, $goal ) {
1822 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
1824 while ( $goal < strlen( $string_nullspace ) ) {
1825 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
1827 if ( false === $pos ) {
1828 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
1829 if ( false === $pos ) {
1834 $chunks[] = substr( $string, 0, $pos + 1 );
1835 $string = substr( $string, $pos + 1 );
1836 $string_nullspace = substr( $string_nullspace, $pos + 1 );
1840 $chunks[] = $string;
1847 * Adds rel nofollow string to all HTML A elements in content.
1851 * @param string $text Content that may contain HTML A elements.
1852 * @return string Converted content.
1854 function wp_rel_nofollow( $text ) {
1855 // This is a pre save filter, so text is already escaped.
1856 $text = stripslashes($text);
1857 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1858 $text = wp_slash($text);
1863 * Callback to add rel=nofollow string to HTML A element.
1865 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1866 * string to prevent from invalidating (X)HTML.
1870 * @param array $matches Single Match
1871 * @return string HTML A Element with rel nofollow.
1873 function wp_rel_nofollow_callback( $matches ) {
1874 $text = $matches[1];
1875 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1876 return "<a $text rel=\"nofollow\">";
1880 * Convert one smiley code to the icon graphic file equivalent.
1882 * Callback handler for {@link convert_smilies()}.
1883 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1884 * <img> string for that smiley.
1886 * @global array $wpsmiliestrans
1889 * @param array $matches Single match. Smiley code to convert to image.
1890 * @return string Image string for smiley.
1892 function translate_smiley( $matches ) {
1893 global $wpsmiliestrans;
1895 if ( count( $matches ) == 0 )
1898 $smiley = trim( reset( $matches ) );
1899 $img = $wpsmiliestrans[ $smiley ];
1902 * Filter the Smiley image URL before it's used in the image element.
1906 * @param string $smiley_url URL for the smiley image.
1907 * @param string $img Filename for the smiley image.
1908 * @param string $site_url Site URL, as returned by site_url().
1910 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
1912 return sprintf( ' <img src="%s" alt="%s" class="wp-smiley" /> ', esc_url( $src_url ), esc_attr( $smiley ) );
1916 * Convert text equivalent of smilies to images.
1918 * Will only convert smilies if the option 'use_smilies' is true and the global
1919 * used in the function isn't empty.
1922 * @uses $wp_smiliessearch
1924 * @param string $text Content to convert smilies from text.
1925 * @return string Converted content with text smilies replaced with images.
1927 function convert_smilies( $text ) {
1928 global $wp_smiliessearch;
1930 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
1931 // HTML loop taken from texturize function, could possible be consolidated
1932 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
1933 $stop = count( $textarr );// loop stuff
1935 // Ignore proessing of specific tags
1936 $tags_to_ignore = 'code|pre|style|script|textarea';
1937 $ignore_block_element = '';
1939 for ( $i = 0; $i < $stop; $i++ ) {
1940 $content = $textarr[$i];
1942 // If we're in an ignore block, wait until we find its closing tag
1943 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
1944 $ignore_block_element = $matches[1];
1947 // If it's not a tag and not in ignore block
1948 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
1949 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
1952 // did we exit ignore block
1953 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
1954 $ignore_block_element = '';
1957 $output .= $content;
1960 // return default text.
1967 * Verifies that an email is valid.
1969 * Does not grok i18n domains. Not RFC compliant.
1973 * @param string $email Email address to verify.
1974 * @param boolean $deprecated Deprecated.
1975 * @return string|bool Either false or the valid email address.
1977 function is_email( $email, $deprecated = false ) {
1978 if ( ! empty( $deprecated ) )
1979 _deprecated_argument( __FUNCTION__, '3.0' );
1981 // Test for the minimum length the email can be
1982 if ( strlen( $email ) < 3 ) {
1984 * Filter whether an email address is valid.
1986 * This filter is evaluated under several different contexts, such as 'email_too_short',
1987 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
1988 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
1992 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
1993 * @param string $email The email address being checked.
1994 * @param string $message An explanatory message to the user.
1995 * @param string $context Context under which the email was tested.
1997 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2000 // Test for an @ character after the first position
2001 if ( strpos( $email, '@', 1 ) === false ) {
2002 /** This filter is documented in wp-includes/formatting.php */
2003 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2006 // Split out the local and domain parts
2007 list( $local, $domain ) = explode( '@', $email, 2 );
2010 // Test for invalid characters
2011 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2012 /** This filter is documented in wp-includes/formatting.php */
2013 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2017 // Test for sequences of periods
2018 if ( preg_match( '/\.{2,}/', $domain ) ) {
2019 /** This filter is documented in wp-includes/formatting.php */
2020 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2023 // Test for leading and trailing periods and whitespace
2024 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2025 /** This filter is documented in wp-includes/formatting.php */
2026 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2029 // Split the domain into subs
2030 $subs = explode( '.', $domain );
2032 // Assume the domain will have at least two subs
2033 if ( 2 > count( $subs ) ) {
2034 /** This filter is documented in wp-includes/formatting.php */
2035 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2038 // Loop through each sub
2039 foreach ( $subs as $sub ) {
2040 // Test for leading and trailing hyphens and whitespace
2041 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2042 /** This filter is documented in wp-includes/formatting.php */
2043 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2046 // Test for invalid characters
2047 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2048 /** This filter is documented in wp-includes/formatting.php */
2049 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2053 // Congratulations your email made it!
2054 /** This filter is documented in wp-includes/formatting.php */
2055 return apply_filters( 'is_email', $email, $email, null );
2059 * Convert to ASCII from email subjects.
2063 * @param string $string Subject line
2064 * @return string Converted string to ASCII
2066 function wp_iso_descrambler($string) {
2067 /* this may only work with iso-8859-1, I'm afraid */
2068 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2071 $subject = str_replace('_', ' ', $matches[2]);
2072 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
2078 * Helper function to convert hex encoded chars to ASCII
2083 * @param array $match The preg_replace_callback matches array
2084 * @return array Converted chars
2086 function _wp_iso_convert( $match ) {
2087 return chr( hexdec( strtolower( $match[1] ) ) );
2091 * Returns a date in the GMT equivalent.
2093 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2094 * timezone_string available, the date is assumed to be in that timezone,
2095 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2096 * format can be overridden using the $format parameter.
2100 * @uses get_option() to retrieve the value of 'gmt_offset'.
2101 * @param string $string The date to be converted.
2102 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2103 * @return string GMT version of the date provided.
2105 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2106 $tz = get_option( 'timezone_string' );
2108 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2110 return gmdate( $format, 0 );
2111 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2112 $string_gmt = $datetime->format( $format );
2114 if ( ! 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 ) )
2115 return gmdate( $format, 0 );
2116 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2117 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2123 * Converts a GMT date into the correct format for the blog.
2125 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2126 * timezone_string available, the returned date is in that timezone, otherwise
2127 * it simply adds the value of gmt_offset. Return format can be overridden
2128 * using the $format parameter
2132 * @param string $string The date to be converted.
2133 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2134 * @return string Formatted date relative to the timezone / GMT offset.
2136 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2137 $tz = get_option( 'timezone_string' );
2139 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2141 return date( $format, 0 );
2142 $datetime->setTimezone( new DateTimeZone( $tz ) );
2143 $string_localtime = $datetime->format( $format );
2145 if ( ! 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) )
2146 return date( $format, 0 );
2147 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2148 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2150 return $string_localtime;
2154 * Computes an offset in seconds from an iso8601 timezone.
2158 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2159 * @return int|float The offset in seconds.
2161 function iso8601_timezone_to_offset($timezone) {
2162 // $timezone is either 'Z' or '[+|-]hhmm'
2163 if ($timezone == 'Z') {
2166 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2167 $hours = intval(substr($timezone, 1, 2));
2168 $minutes = intval(substr($timezone, 3, 4)) / 60;
2169 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2175 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2179 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2180 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2181 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2183 function iso8601_to_datetime($date_string, $timezone = 'user') {
2184 $timezone = strtolower($timezone);
2186 if ($timezone == 'gmt') {
2188 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);
2190 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2191 $offset = iso8601_timezone_to_offset($date_bits[7]);
2192 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2193 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2196 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2197 $timestamp -= $offset;
2199 return gmdate('Y-m-d H:i:s', $timestamp);
2201 } else if ($timezone == 'user') {
2202 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);
2207 * Adds a element attributes to open links in new windows.
2209 * Comment text in popup windows should be filtered through this. Right now it's
2210 * a moderately dumb function, ideally it would detect whether a target or rel
2211 * attribute was already there and adjust its actions accordingly.
2215 * @param string $text Content to replace links to open in a new window.
2216 * @return string Content that has filtered links.
2218 function popuplinks($text) {
2219 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2224 * Strips out all characters that are not allowable in an email.
2228 * @param string $email Email address to filter.
2229 * @return string Filtered email address.
2231 function sanitize_email( $email ) {
2232 // Test for the minimum length the email can be
2233 if ( strlen( $email ) < 3 ) {
2235 * Filter a sanitized email address.
2237 * This filter is evaluated under several contexts, including 'email_too_short',
2238 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2239 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2243 * @param string $email The sanitized email address.
2244 * @param string $email The email address, as provided to sanitize_email().
2245 * @param string $message A message to pass to the user.
2247 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2250 // Test for an @ character after the first position
2251 if ( strpos( $email, '@', 1 ) === false ) {
2252 /** This filter is documented in wp-includes/formatting.php */
2253 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2256 // Split out the local and domain parts
2257 list( $local, $domain ) = explode( '@', $email, 2 );
2260 // Test for invalid characters
2261 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2262 if ( '' === $local ) {
2263 /** This filter is documented in wp-includes/formatting.php */
2264 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2268 // Test for sequences of periods
2269 $domain = preg_replace( '/\.{2,}/', '', $domain );
2270 if ( '' === $domain ) {
2271 /** This filter is documented in wp-includes/formatting.php */
2272 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2275 // Test for leading and trailing periods and whitespace
2276 $domain = trim( $domain, " \t\n\r\0\x0B." );
2277 if ( '' === $domain ) {
2278 /** This filter is documented in wp-includes/formatting.php */
2279 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2282 // Split the domain into subs
2283 $subs = explode( '.', $domain );
2285 // Assume the domain will have at least two subs
2286 if ( 2 > count( $subs ) ) {
2287 /** This filter is documented in wp-includes/formatting.php */
2288 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2291 // Create an array that will contain valid subs
2292 $new_subs = array();
2294 // Loop through each sub
2295 foreach ( $subs as $sub ) {
2296 // Test for leading and trailing hyphens
2297 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2299 // Test for invalid characters
2300 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2302 // If there's anything left, add it to the valid subs
2303 if ( '' !== $sub ) {
2308 // If there aren't 2 or more valid subs
2309 if ( 2 > count( $new_subs ) ) {
2310 /** This filter is documented in wp-includes/formatting.php */
2311 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2314 // Join valid subs into the new domain
2315 $domain = join( '.', $new_subs );
2317 // Put the email back together
2318 $email = $local . '@' . $domain;
2320 // Congratulations your email made it!
2321 /** This filter is documented in wp-includes/formatting.php */
2322 return apply_filters( 'sanitize_email', $email, $email, null );
2326 * Determines the difference between two timestamps.
2328 * The difference is returned in a human readable format such as "1 hour",
2329 * "5 mins", "2 days".
2333 * @param int $from Unix timestamp from which the difference begins.
2334 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2335 * @return string Human readable time difference.
2337 function human_time_diff( $from, $to = '' ) {
2341 $diff = (int) abs( $to - $from );
2343 if ( $diff < HOUR_IN_SECONDS ) {
2344 $mins = round( $diff / MINUTE_IN_SECONDS );
2347 /* translators: min=minute */
2348 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2349 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2350 $hours = round( $diff / HOUR_IN_SECONDS );
2353 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2354 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2355 $days = round( $diff / DAY_IN_SECONDS );
2358 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2359 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2360 $weeks = round( $diff / WEEK_IN_SECONDS );
2363 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2364 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2365 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2368 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2369 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2370 $years = round( $diff / YEAR_IN_SECONDS );
2373 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2380 * Generates an excerpt from the content, if needed.
2382 * The excerpt word amount will be 55 words and if the amount is greater than
2383 * that, then the string ' […]' will be appended to the excerpt. If the string
2384 * is less than 55 words, then the content will be returned as is.
2386 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2387 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2391 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2392 * @return string The excerpt.
2394 function wp_trim_excerpt($text = '') {
2395 $raw_excerpt = $text;
2396 if ( '' == $text ) {
2397 $text = get_the_content('');
2399 $text = strip_shortcodes( $text );
2401 /** This filter is documented in wp-includes/post-template.php */
2402 $text = apply_filters( 'the_content', $text );
2403 $text = str_replace(']]>', ']]>', $text);
2406 * Filter the number of words in an excerpt.
2410 * @param int $number The number of words. Default 55.
2412 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2414 * Filter the string in the "more" link displayed after a trimmed excerpt.
2418 * @param string $more_string The string shown within the more link.
2420 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2421 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2424 * Filter the trimmed excerpt string.
2428 * @param string $text The trimmed text.
2429 * @param string $raw_excerpt The text prior to trimming.
2431 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2435 * Trims text to a certain number of words.
2437 * This function is localized. For languages that count 'words' by the individual
2438 * character (such as East Asian languages), the $num_words argument will apply
2439 * to the number of individual characters.
2443 * @param string $text Text to trim.
2444 * @param int $num_words Number of words. Default 55.
2445 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2446 * @return string Trimmed text.
2448 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2449 if ( null === $more )
2450 $more = __( '…' );
2451 $original_text = $text;
2452 $text = wp_strip_all_tags( $text );
2453 /* translators: If your word count is based on single characters (East Asian characters),
2454 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2455 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2456 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2457 preg_match_all( '/./u', $text, $words_array );
2458 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2461 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2464 if ( count( $words_array ) > $num_words ) {
2465 array_pop( $words_array );
2466 $text = implode( $sep, $words_array );
2467 $text = $text . $more;
2469 $text = implode( $sep, $words_array );
2472 * Filter the text content after words have been trimmed.
2476 * @param string $text The trimmed text.
2477 * @param int $num_words The number of words to trim the text to. Default 5.
2478 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2479 * @param string $original_text The text before it was trimmed.
2481 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2485 * Converts named entities into numbered entities.
2489 * @param string $text The text within which entities will be converted.
2490 * @return string Text with converted entities.
2492 function ent2ncr($text) {
2495 * Filter text before named entities are converted into numbered entities.
2497 * A non-null string must be returned for the filter to be evaluated.
2501 * @param null $converted_text The text to be converted. Default null.
2502 * @param string $text The text prior to entity conversion.
2504 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2505 if( null !== $filtered )
2509 '"' => '"',
2514 ' ' => ' ',
2515 '¡' => '¡',
2516 '¢' => '¢',
2517 '£' => '£',
2518 '¤' => '¤',
2519 '¥' => '¥',
2520 '¦' => '¦',
2521 '&brkbar;' => '¦',
2522 '§' => '§',
2523 '¨' => '¨',
2524 '¨' => '¨',
2525 '©' => '©',
2526 'ª' => 'ª',
2527 '«' => '«',
2528 '¬' => '¬',
2529 '­' => '­',
2530 '®' => '®',
2531 '¯' => '¯',
2532 '&hibar;' => '¯',
2533 '°' => '°',
2534 '±' => '±',
2535 '²' => '²',
2536 '³' => '³',
2537 '´' => '´',
2538 'µ' => 'µ',
2539 '¶' => '¶',
2540 '·' => '·',
2541 '¸' => '¸',
2542 '¹' => '¹',
2543 'º' => 'º',
2544 '»' => '»',
2545 '¼' => '¼',
2546 '½' => '½',
2547 '¾' => '¾',
2548 '¿' => '¿',
2549 'À' => 'À',
2550 'Á' => 'Á',
2551 'Â' => 'Â',
2552 'Ã' => 'Ã',
2553 'Ä' => 'Ä',
2554 'Å' => 'Å',
2555 'Æ' => 'Æ',
2556 'Ç' => 'Ç',
2557 'È' => 'È',
2558 'É' => 'É',
2559 'Ê' => 'Ê',
2560 'Ë' => 'Ë',
2561 'Ì' => 'Ì',
2562 'Í' => 'Í',
2563 'Î' => 'Î',
2564 'Ï' => 'Ï',
2565 'Ð' => 'Ð',
2566 'Ñ' => 'Ñ',
2567 'Ò' => 'Ò',
2568 'Ó' => 'Ó',
2569 'Ô' => 'Ô',
2570 'Õ' => 'Õ',
2571 'Ö' => 'Ö',
2572 '×' => '×',
2573 'Ø' => 'Ø',
2574 'Ù' => 'Ù',
2575 'Ú' => 'Ú',
2576 'Û' => 'Û',
2577 'Ü' => 'Ü',
2578 'Ý' => 'Ý',
2579 'Þ' => 'Þ',
2580 'ß' => 'ß',
2581 'à' => 'à',
2582 'á' => 'á',
2583 'â' => 'â',
2584 'ã' => 'ã',
2585 'ä' => 'ä',
2586 'å' => 'å',
2587 'æ' => 'æ',
2588 'ç' => 'ç',
2589 'è' => 'è',
2590 'é' => 'é',
2591 'ê' => 'ê',
2592 'ë' => 'ë',
2593 'ì' => 'ì',
2594 'í' => 'í',
2595 'î' => 'î',
2596 'ï' => 'ï',
2597 'ð' => 'ð',
2598 'ñ' => 'ñ',
2599 'ò' => 'ò',
2600 'ó' => 'ó',
2601 'ô' => 'ô',
2602 'õ' => 'õ',
2603 'ö' => 'ö',
2604 '÷' => '÷',
2605 'ø' => 'ø',
2606 'ù' => 'ù',
2607 'ú' => 'ú',
2608 'û' => 'û',
2609 'ü' => 'ü',
2610 'ý' => 'ý',
2611 'þ' => 'þ',
2612 'ÿ' => 'ÿ',
2613 'Œ' => 'Œ',
2614 'œ' => 'œ',
2615 'Š' => 'Š',
2616 'š' => 'š',
2617 'Ÿ' => 'Ÿ',
2618 'ƒ' => 'ƒ',
2619 'ˆ' => 'ˆ',
2620 '˜' => '˜',
2621 'Α' => 'Α',
2622 'Β' => 'Β',
2623 'Γ' => 'Γ',
2624 'Δ' => 'Δ',
2625 'Ε' => 'Ε',
2626 'Ζ' => 'Ζ',
2627 'Η' => 'Η',
2628 'Θ' => 'Θ',
2629 'Ι' => 'Ι',
2630 'Κ' => 'Κ',
2631 'Λ' => 'Λ',
2635 'Ο' => 'Ο',
2637 'Ρ' => 'Ρ',
2638 'Σ' => 'Σ',
2639 'Τ' => 'Τ',
2640 'Υ' => 'Υ',
2641 'Φ' => 'Φ',
2642 'Χ' => 'Χ',
2643 'Ψ' => 'Ψ',
2644 'Ω' => 'Ω',
2645 'α' => 'α',
2646 'β' => 'β',
2647 'γ' => 'γ',
2648 'δ' => 'δ',
2649 'ε' => 'ε',
2650 'ζ' => 'ζ',
2651 'η' => 'η',
2652 'θ' => 'θ',
2653 'ι' => 'ι',
2654 'κ' => 'κ',
2655 'λ' => 'λ',
2659 'ο' => 'ο',
2661 'ρ' => 'ρ',
2662 'ς' => 'ς',
2663 'σ' => 'σ',
2664 'τ' => 'τ',
2665 'υ' => 'υ',
2666 'φ' => 'φ',
2667 'χ' => 'χ',
2668 'ψ' => 'ψ',
2669 'ω' => 'ω',
2670 'ϑ' => 'ϑ',
2671 'ϒ' => 'ϒ',
2672 'ϖ' => 'ϖ',
2673 ' ' => ' ',
2674 ' ' => ' ',
2675 ' ' => ' ',
2676 '‌' => '‌',
2677 '‍' => '‍',
2678 '‎' => '‎',
2679 '‏' => '‏',
2680 '–' => '–',
2681 '—' => '—',
2682 '‘' => '‘',
2683 '’' => '’',
2684 '‚' => '‚',
2685 '“' => '“',
2686 '”' => '”',
2687 '„' => '„',
2688 '†' => '†',
2689 '‡' => '‡',
2690 '•' => '•',
2691 '…' => '…',
2692 '‰' => '‰',
2693 '′' => '′',
2694 '″' => '″',
2695 '‹' => '‹',
2696 '›' => '›',
2697 '‾' => '‾',
2698 '⁄' => '⁄',
2699 '€' => '€',
2700 'ℑ' => 'ℑ',
2701 '℘' => '℘',
2702 'ℜ' => 'ℜ',
2703 '™' => '™',
2704 'ℵ' => 'ℵ',
2705 '↵' => '↵',
2706 '⇐' => '⇐',
2707 '⇑' => '⇑',
2708 '⇒' => '⇒',
2709 '⇓' => '⇓',
2710 '⇔' => '⇔',
2711 '∀' => '∀',
2712 '∂' => '∂',
2713 '∃' => '∃',
2714 '∅' => '∅',
2715 '∇' => '∇',
2716 '∈' => '∈',
2717 '∉' => '∉',
2718 '∋' => '∋',
2719 '∏' => '∏',
2720 '∑' => '∑',
2721 '−' => '−',
2722 '∗' => '∗',
2723 '√' => '√',
2724 '∝' => '∝',
2725 '∞' => '∞',
2726 '∠' => '∠',
2727 '∧' => '∧',
2728 '∨' => '∨',
2729 '∩' => '∩',
2730 '∪' => '∪',
2731 '∫' => '∫',
2732 '∴' => '∴',
2733 '∼' => '∼',
2734 '≅' => '≅',
2735 '≈' => '≈',
2736 '≠' => '≠',
2737 '≡' => '≡',
2738 '≤' => '≤',
2739 '≥' => '≥',
2740 '⊂' => '⊂',
2741 '⊃' => '⊃',
2742 '⊄' => '⊄',
2743 '⊆' => '⊆',
2744 '⊇' => '⊇',
2745 '⊕' => '⊕',
2746 '⊗' => '⊗',
2747 '⊥' => '⊥',
2748 '⋅' => '⋅',
2749 '⌈' => '⌈',
2750 '⌉' => '⌉',
2751 '⌊' => '⌊',
2752 '⌋' => '⌋',
2753 '⟨' => '〈',
2754 '⟩' => '〉',
2755 '←' => '←',
2756 '↑' => '↑',
2757 '→' => '→',
2758 '↓' => '↓',
2759 '↔' => '↔',
2760 '◊' => '◊',
2761 '♠' => '♠',
2762 '♣' => '♣',
2763 '♥' => '♥',
2764 '♦' => '♦'
2767 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2771 * Formats text for the rich text editor.
2773 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2774 * be applied to an empty string.
2778 * @param string $text The text to be formatted.
2779 * @return string The formatted text after filter is applied.
2781 function wp_richedit_pre($text) {
2782 if ( empty( $text ) ) {
2784 * Filter text returned for the rich text editor.
2786 * This filter is first evaluated, and the value returned, if an empty string
2787 * is passed to wp_richedit_pre(). If an empty string is passed, it results
2788 * in a break tag and line feed.
2790 * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
2791 * return after being formatted.
2795 * @param string $output Text for the rich text editor.
2797 return apply_filters( 'richedit_pre', '' );
2800 $output = convert_chars($text);
2801 $output = wpautop($output);
2802 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
2804 /** This filter is documented in wp-includes/formatting.php */
2805 return apply_filters( 'richedit_pre', $output );
2809 * Formats text for the HTML editor.
2811 * Unless $output is empty it will pass through htmlspecialchars before the
2812 * 'htmledit_pre' filter is applied.
2816 * @param string $output The text to be formatted.
2817 * @return string Formatted text after filter applied.
2819 function wp_htmledit_pre($output) {
2820 if ( !empty($output) )
2821 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
2824 * Filter the text before it is formatted for the HTML editor.
2828 * @param string $output The HTML-formatted text.
2830 return apply_filters( 'htmledit_pre', $output );
2834 * Perform a deep string replace operation to ensure the values in $search are no longer present
2836 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2837 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2838 * str_replace would return
2843 * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
2844 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
2845 * @return string The string with the replaced svalues.
2847 function _deep_replace( $search, $subject ) {
2848 $subject = (string) $subject;
2852 $subject = str_replace( $search, '', $subject, $count );
2859 * Escapes data for use in a MySQL query.
2861 * Usually you should prepare queries using wpdb::prepare().
2862 * Sometimes, spot-escaping is required or useful. One example
2863 * is preparing an array for use in an IN clause.
2866 * @param string|array $data Unescaped data
2867 * @return string|array Escaped data
2869 function esc_sql( $data ) {
2871 return $wpdb->_escape( $data );
2875 * Checks and cleans a URL.
2877 * A number of characters are removed from the URL. If the URL is for displaying
2878 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
2879 * is applied to the returned cleaned URL.
2882 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2883 * via $protocols or the common ones set in the function.
2885 * @param string $url The URL to be cleaned.
2886 * @param array $protocols Optional. An array of acceptable protocols.
2887 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
2888 * @param string $_context Private. Use esc_url_raw() for database usage.
2889 * @return string The cleaned $url after the 'clean_url' filter is applied.
2891 function esc_url( $url, $protocols = null, $_context = 'display' ) {
2892 $original_url = $url;
2896 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2897 $strip = array('%0d', '%0a', '%0D', '%0A');
2898 $url = _deep_replace($strip, $url);
2899 $url = str_replace(';//', '://', $url);
2900 /* If the URL doesn't appear to contain a scheme, we
2901 * presume it needs http:// appended (unless a relative
2902 * link starting with /, # or ? or a php file).
2904 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
2905 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2906 $url = 'http://' . $url;
2908 // Replace ampersands and single quotes only when displaying.
2909 if ( 'display' == $_context ) {
2910 $url = wp_kses_normalize_entities( $url );
2911 $url = str_replace( '&', '&', $url );
2912 $url = str_replace( "'", ''', $url );
2915 if ( '/' === $url[0] ) {
2916 $good_protocol_url = $url;
2918 if ( ! is_array( $protocols ) )
2919 $protocols = wp_allowed_protocols();
2920 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
2921 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
2926 * Filter a string cleaned and escaped for output as a URL.
2930 * @param string $good_protocol_url The cleaned URL to be returned.
2931 * @param string $original_url The URL prior to cleaning.
2932 * @param string $_context If 'display', replace ampersands and single quotes only.
2934 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
2938 * Performs esc_url() for database usage.
2943 * @param string $url The URL to be cleaned.
2944 * @param array $protocols An array of acceptable protocols.
2945 * @return string The cleaned URL.
2947 function esc_url_raw( $url, $protocols = null ) {
2948 return esc_url( $url, $protocols, 'db' );
2952 * Convert entities, while preserving already-encoded entities.
2954 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2958 * @param string $myHTML The text to be converted.
2959 * @return string Converted text.
2961 function htmlentities2($myHTML) {
2962 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2963 $translation_table[chr(38)] = '&';
2964 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
2968 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2970 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
2971 * (in a tag attribute, for example onclick="..."). Note that the strings have to
2972 * be in single quotes. The filter 'js_escape' is also applied here.
2976 * @param string $text The text to be escaped.
2977 * @return string Escaped text.
2979 function esc_js( $text ) {
2980 $safe_text = wp_check_invalid_utf8( $text );
2981 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2982 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2983 $safe_text = str_replace( "\r", '', $safe_text );
2984 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2986 * Filter a string cleaned and escaped for output in JavaScript.
2988 * Text passed to esc_js() is stripped of invalid or special characters,
2989 * and properly slashed for output.
2993 * @param string $safe_text The text after it has been escaped.
2994 * @param string $text The text prior to being escaped.
2996 return apply_filters( 'js_escape', $safe_text, $text );
3000 * Escaping for HTML blocks.
3004 * @param string $text
3007 function esc_html( $text ) {
3008 $safe_text = wp_check_invalid_utf8( $text );
3009 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3011 * Filter a string cleaned and escaped for output in HTML.
3013 * Text passed to esc_html() is stripped of invalid or special characters
3018 * @param string $safe_text The text after it has been escaped.
3019 * @param string $text The text prior to being escaped.
3021 return apply_filters( 'esc_html', $safe_text, $text );
3025 * Escaping for HTML attributes.
3029 * @param string $text
3032 function esc_attr( $text ) {
3033 $safe_text = wp_check_invalid_utf8( $text );
3034 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3036 * Filter a string cleaned and escaped for output in an HTML attribute.
3038 * Text passed to esc_attr() is stripped of invalid or special characters
3043 * @param string $safe_text The text after it has been escaped.
3044 * @param string $text The text prior to being escaped.
3046 return apply_filters( 'attribute_escape', $safe_text, $text );
3050 * Escaping for textarea values.
3054 * @param string $text
3057 function esc_textarea( $text ) {
3058 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3060 * Filter a string cleaned and escaped for output in a textarea element.
3064 * @param string $safe_text The text after it has been escaped.
3065 * @param string $text The text prior to being escaped.
3067 return apply_filters( 'esc_textarea', $safe_text, $text );
3071 * Escape an HTML tag name.
3075 * @param string $tag_name
3078 function tag_escape($tag_name) {
3079 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3081 * Filter a string cleaned and escaped for output as an HTML tag.
3085 * @param string $safe_tag The tag name after it has been escaped.
3086 * @param string $tag_name The text before it was escaped.
3088 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3092 * Escapes text for SQL LIKE special characters % and _.
3096 * @param string $text The text to be escaped.
3097 * @return string text, safe for inclusion in LIKE query.
3099 function like_escape($text) {
3100 return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
3104 * Convert full URL paths to absolute paths.
3106 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3107 * beginning, so it isn't a true relative link, but from the web root base.
3111 * @param string $link Full URL path.
3112 * @return string Absolute path.
3114 function wp_make_link_relative( $link ) {
3115 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
3119 * Sanitises various option values based on the nature of the option.
3121 * This is basically a switch statement which will pass $value through a number
3122 * of functions depending on the $option.
3126 * @param string $option The name of the option.
3127 * @param string $value The unsanitised value.
3128 * @return string Sanitized value.
3130 function sanitize_option($option, $value) {
3132 switch ( $option ) {
3133 case 'admin_email' :
3134 case 'new_admin_email' :
3135 $value = sanitize_email( $value );
3136 if ( ! is_email( $value ) ) {
3137 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3138 if ( function_exists( 'add_settings_error' ) )
3139 add_settings_error( $option, 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) );
3143 case 'thumbnail_size_w':
3144 case 'thumbnail_size_h':
3145 case 'medium_size_w':
3146 case 'medium_size_h':
3147 case 'large_size_w':
3148 case 'large_size_h':
3149 case 'mailserver_port':
3150 case 'comment_max_links':
3151 case 'page_on_front':
3152 case 'page_for_posts':
3153 case 'rss_excerpt_length':
3154 case 'default_category':
3155 case 'default_email_category':
3156 case 'default_link_category':
3157 case 'close_comments_days_old':
3158 case 'comments_per_page':
3159 case 'thread_comments_depth':
3160 case 'users_can_register':
3161 case 'start_of_week':
3162 $value = absint( $value );
3165 case 'posts_per_page':
3166 case 'posts_per_rss':
3167 $value = (int) $value;
3168 if ( empty($value) )
3171 $value = abs($value);
3174 case 'default_ping_status':
3175 case 'default_comment_status':
3176 // Options that if not there have 0 value but need to be something like "closed"
3177 if ( $value == '0' || $value == '')
3181 case 'blogdescription':
3183 $value = wp_kses_post( $value );
3184 $value = esc_html( $value );
3187 case 'blog_charset':
3188 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3192 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3193 if ( null === $value )
3196 $value = intval( $value );
3201 case 'mailserver_url':
3202 case 'mailserver_login':
3203 case 'mailserver_pass':
3205 $value = strip_tags( $value );
3206 $value = wp_kses_data( $value );
3210 $value = explode( "\n", $value );
3211 $value = array_filter( array_map( 'trim', $value ) );
3212 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3213 $value = implode( "\n", $value );
3217 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3221 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3222 $value = esc_url_raw($value);
3224 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3225 if ( function_exists('add_settings_error') )
3226 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3231 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3232 $value = esc_url_raw($value);
3234 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3235 if ( function_exists('add_settings_error') )
3236 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3241 $allowed = get_available_languages();
3242 if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
3243 $value = get_option( $option );
3246 case 'illegal_names':
3247 if ( ! is_array( $value ) )
3248 $value = explode( ' ', $value );
3250 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3256 case 'limited_email_domains':
3257 case 'banned_email_domains':
3258 if ( ! is_array( $value ) )
3259 $value = explode( "\n", $value );
3261 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3264 foreach ( $domains as $domain ) {
3265 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
3272 case 'timezone_string':
3273 $allowed_zones = timezone_identifiers_list();
3274 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3275 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3276 if ( function_exists('add_settings_error') )
3277 add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
3281 case 'permalink_structure':
3282 case 'category_base':
3284 $value = esc_url_raw( $value );
3285 $value = str_replace( 'http://', '', $value );
3288 case 'default_role' :
3289 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3290 $value = 'subscriber';
3295 * Filter an option value following sanitization.
3299 * @param string $value The sanitized option value.
3300 * @param string $option The option name.
3302 $value = apply_filters( "sanitize_option_{$option}", $value, $option );
3308 * Parses a string into variables to be stored in an array.
3310 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3311 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3315 * @param string $string The string to be parsed.
3316 * @param array $array Variables will be stored in this array.
3318 function wp_parse_str( $string, &$array ) {
3319 parse_str( $string, $array );
3320 if ( get_magic_quotes_gpc() )
3321 $array = stripslashes_deep( $array );
3323 * Filter the array of variables derived from a parsed string.
3327 * @param array $array The array populated with variables.
3329 $array = apply_filters( 'wp_parse_str', $array );
3333 * Convert lone less than signs.
3335 * KSES already converts lone greater than signs.
3337 * @uses wp_pre_kses_less_than_callback in the callback function.
3340 * @param string $text Text to be converted.
3341 * @return string Converted text.
3343 function wp_pre_kses_less_than( $text ) {
3344 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3348 * Callback function used by preg_replace.
3350 * @uses esc_html to format the $matches text.
3353 * @param array $matches Populated by matches to preg_replace.
3354 * @return string The text returned after esc_html if needed.
3356 function wp_pre_kses_less_than_callback( $matches ) {
3357 if ( false === strpos($matches[0], '>') )
3358 return esc_html($matches[0]);
3363 * WordPress implementation of PHP sprintf() with filters.
3366 * @link http://www.php.net/sprintf
3368 * @param string $pattern The string which formatted args are inserted.
3369 * @param mixed $args,... Arguments to be formatted into the $pattern string.
3370 * @return string The formatted string.
3372 function wp_sprintf( $pattern ) {
3373 $args = func_get_args();
3374 $len = strlen($pattern);
3378 while ( $len > $start ) {
3379 // Last character: append and break
3380 if ( strlen($pattern) - 1 == $start ) {
3381 $result .= substr($pattern, -1);
3385 // Literal %: append and continue
3386 if ( substr($pattern, $start, 2) == '%%' ) {
3392 // Get fragment before next %
3393 $end = strpos($pattern, '%', $start + 1);
3394 if ( false === $end )
3396 $fragment = substr($pattern, $start, $end - $start);
3398 // Fragment has a specifier
3399 if ( $pattern[$start] == '%' ) {
3400 // Find numbered arguments or take the next one in order
3401 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3402 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3403 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3406 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3410 * Filter a fragment from the pattern passed to wp_sprintf().
3412 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3416 * @param string $fragment A fragment from the pattern.
3417 * @param string $arg The argument.
3419 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3420 if ( $_fragment != $fragment )
3421 $fragment = $_fragment;
3423 $fragment = sprintf($fragment, strval($arg) );
3426 // Append to result and move to next fragment
3427 $result .= $fragment;
3434 * Localize list items before the rest of the content.
3436 * The '%l' must be at the first characters can then contain the rest of the
3437 * content. The list items will have ', ', ', and', and ' and ' added depending
3438 * on the amount of list items in the $args parameter.
3442 * @param string $pattern Content containing '%l' at the beginning.
3443 * @param array $args List items to prepend to the content and replace '%l'.
3444 * @return string Localized list items and rest of the content.
3446 function wp_sprintf_l($pattern, $args) {
3448 if ( substr($pattern, 0, 2) != '%l' )
3451 // Nothing to work with
3456 * Filter the translated delimiters used by wp_sprintf_l().
3457 * Placeholders (%s) are included to assist translators and then
3458 * removed before the array of strings reaches the filter.
3460 * Please note: Ampersands and entities should be avoided here.
3464 * @param array $delimiters An array of translated delimiters.
3466 $l = apply_filters( 'wp_sprintf_l', array(
3467 /* translators: used to join items in a list with more than 2 items */
3468 'between' => sprintf( __('%s, %s'), '', '' ),
3469 /* translators: used to join last two items in a list with more than 2 times */
3470 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3471 /* translators: used to join items in a list with only 2 items */
3472 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3475 $args = (array) $args;
3476 $result = array_shift($args);
3477 if ( count($args) == 1 )
3478 $result .= $l['between_only_two'] . array_shift($args);
3479 // Loop when more than two args
3482 $arg = array_shift($args);
3485 $result .= $l['between_last_two'] . $arg;
3487 $result .= $l['between'] . $arg;
3489 return $result . substr($pattern, 2);
3493 * Safely extracts not more than the first $count characters from html string.
3495 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3496 * be counted as one character. For example & will be counted as 4, < as
3501 * @param string $str String to get the excerpt from.
3502 * @param integer $count Maximum number of characters to take.
3503 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3504 * @return string The excerpt.
3506 function wp_html_excerpt( $str, $count, $more = null ) {
3507 if ( null === $more )
3509 $str = wp_strip_all_tags( $str, true );
3510 $excerpt = mb_substr( $str, 0, $count );
3511 // remove part of an entity at the end
3512 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3513 if ( $str != $excerpt )
3514 $excerpt = trim( $excerpt ) . $more;
3519 * Add a Base url to relative links in passed content.
3521 * By default it supports the 'src' and 'href' attributes. However this can be
3522 * changed via the 3rd param.
3526 * @param string $content String to search for links in.
3527 * @param string $base The base URL to prefix to links.
3528 * @param array $attrs The attributes which should be processed.
3529 * @return string The processed content.
3531 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3532 global $_links_add_base;
3533 $_links_add_base = $base;
3534 $attrs = implode('|', (array)$attrs);
3535 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3539 * Callback to add a base url to relative links in passed content.
3544 * @param string $m The matched link.
3545 * @return string The processed link.
3547 function _links_add_base($m) {
3548 global $_links_add_base;
3549 //1 = attribute name 2 = quotation mark 3 = URL
3550 return $m[1] . '=' . $m[2] .
3551 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3553 path_join( $_links_add_base, $m[3] ) )
3558 * Adds a Target attribute to all links in passed content.
3560 * This function by default only applies to <a> tags, however this can be
3561 * modified by the 3rd param.
3563 * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
3567 * @param string $content String to search for links in.
3568 * @param string $target The Target to add to the links.
3569 * @param array $tags An array of tags to apply to.
3570 * @return string The processed content.
3572 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3573 global $_links_add_target;
3574 $_links_add_target = $target;
3575 $tags = implode('|', (array)$tags);
3576 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
3580 * Callback to add a target attribute to all links in passed content.
3585 * @param string $m The matched link.
3586 * @return string The processed link.
3588 function _links_add_target( $m ) {
3589 global $_links_add_target;
3591 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
3592 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3596 * Normalize EOL characters and strip duplicate whitespace.
3600 * @param string $str The string to normalize.
3601 * @return string The normalized string.
3603 function normalize_whitespace( $str ) {
3604 $str = trim( $str );
3605 $str = str_replace( "\r", "\n", $str );
3606 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3611 * Properly strip all HTML tags including script and style
3613 * This differs from strip_tags() because it removes the contents of
3614 * the <script> and <style> tags. E.g. strip_tags( '<script>something</script>' )
3615 * will return 'something'. wp_strip_all_tags will return ''
3619 * @param string $string String containing HTML tags
3620 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3621 * @return string The processed string.
3623 function wp_strip_all_tags($string, $remove_breaks = false) {
3624 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3625 $string = strip_tags($string);
3627 if ( $remove_breaks )
3628 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3630 return trim( $string );
3634 * Sanitize a string from user input or from the db
3636 * check for invalid UTF-8,
3637 * Convert single < characters to entity,
3639 * remove line breaks, tabs and extra white space,
3644 * @param string $str
3647 function sanitize_text_field($str) {
3648 $filtered = wp_check_invalid_utf8( $str );
3650 if ( strpos($filtered, '<') !== false ) {
3651 $filtered = wp_pre_kses_less_than( $filtered );
3652 // This will strip extra whitespace for us.
3653 $filtered = wp_strip_all_tags( $filtered, true );
3655 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
3659 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
3660 $filtered = str_replace($match[0], '', $filtered);
3665 // Strip out the whitespace that may now exist after removing the octets.
3666 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
3670 * Filter a sanitized text field string.
3674 * @param string $filtered The sanitized string.
3675 * @param string $str The string prior to being sanitized.
3677 return apply_filters( 'sanitize_text_field', $filtered, $str );
3681 * i18n friendly version of basename()
3685 * @param string $path A path.
3686 * @param string $suffix If the filename ends in suffix this will also be cut off.
3689 function wp_basename( $path, $suffix = '' ) {
3690 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
3694 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
3696 * Violating our coding standards for a good function name.
3700 function capital_P_dangit( $text ) {
3701 // Simple replacement for titles
3702 $current_filter = current_filter();
3703 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
3704 return str_replace( 'Wordpress', 'WordPress', $text );
3705 // Still here? Use the more judicious replacement
3706 static $dblq = false;
3707 if ( false === $dblq )
3708 $dblq = _x( '“', 'opening curly double quote' );
3710 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
3711 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
3717 * Sanitize a mime type
3721 * @param string $mime_type Mime type
3722 * @return string Sanitized mime type
3724 function sanitize_mime_type( $mime_type ) {
3725 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3727 * Filter a mime type following sanitization.
3731 * @param string $sani_mime_type The sanitized mime type.
3732 * @param string $mime_type The mime type prior to sanitization.
3734 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
3738 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
3742 * @param string $to_ping Space or carriage return separated URLs
3743 * @return string URLs starting with the http or https protocol, separated by a carriage return.
3745 function sanitize_trackback_urls( $to_ping ) {
3746 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
3747 foreach ( $urls_to_ping as $k => $url ) {
3748 if ( !preg_match( '#^https?://.#i', $url ) )
3749 unset( $urls_to_ping[$k] );
3751 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
3752 $urls_to_ping = implode( "\n", $urls_to_ping );
3754 * Filter a list of trackback URLs following sanitization.
3756 * The string returned here consists of a space or carriage return-delimited list
3757 * of trackback URLs.
3761 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
3762 * @param string $to_ping Space or carriage return separated URLs before sanitization.
3764 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
3768 * Add slashes to a string or array of strings.
3770 * This should be used when preparing data for core API that expects slashed data.
3771 * This should not be used to escape data going directly into an SQL query.
3775 * @param string|array $value String or array of strings to slash.
3776 * @return string|array Slashed $value
3778 function wp_slash( $value ) {
3779 if ( is_array( $value ) ) {
3780 foreach ( $value as $k => $v ) {
3781 if ( is_array( $v ) ) {
3782 $value[$k] = wp_slash( $v );
3784 $value[$k] = addslashes( $v );
3788 $value = addslashes( $value );
3795 * Remove slashes from a string or array of strings.
3797 * This should be used to remove slashes from data passed to core API that
3798 * expects data to be unslashed.
3802 * @param string|array $value String or array of strings to unslash.
3803 * @return string|array Unslashed $value
3805 function wp_unslash( $value ) {
3806 return stripslashes_deep( $value );
3810 * Extract and return the first URL from passed content.
3814 * @param string $content A string which might contain a URL.
3815 * @return string The found URL.
3817 function get_url_in_content( $content ) {
3818 if ( empty( $content ) ) {
3822 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
3823 return esc_url_raw( $matches[2] );