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 * @param bool $reset Set to true for unit testing. Translated patterns will reset.
28 * @return string The string replaced with html entities
30 function wptexturize($text, $reset = false) {
31 global $wp_cockneyreplace, $shortcode_tags;
32 static $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
33 $default_no_texturize_tags, $default_no_texturize_shortcodes, $run_texturize = true;
35 // If there's nothing to do, just stop.
36 if ( empty( $text ) || false === $run_texturize ) {
40 // Set up static variables. Run once only.
41 if ( $reset || ! isset( $static_characters ) ) {
43 * Filter whether to skip running wptexturize().
45 * Passing false to the filter will effectively short-circuit wptexturize().
46 * returning the original text passed to the function instead.
48 * The filter runs only once, the first time wptexturize() is called.
54 * @param bool $run_texturize Whether to short-circuit wptexturize().
56 $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
57 if ( false === $run_texturize ) {
61 /* translators: opening curly double quote */
62 $opening_quote = _x( '“', 'opening curly double quote' );
63 /* translators: closing curly double quote */
64 $closing_quote = _x( '”', 'closing curly double quote' );
66 /* translators: apostrophe, for example in 'cause or can't */
67 $apos = _x( '’', 'apostrophe' );
69 /* translators: prime, for example in 9' (nine feet) */
70 $prime = _x( '′', 'prime' );
71 /* translators: double prime, for example in 9" (nine inches) */
72 $double_prime = _x( '″', 'double prime' );
74 /* translators: opening curly single quote */
75 $opening_single_quote = _x( '‘', 'opening curly single quote' );
76 /* translators: closing curly single quote */
77 $closing_single_quote = _x( '’', 'closing curly single quote' );
79 /* translators: en dash */
80 $en_dash = _x( '–', 'en dash' );
81 /* translators: em dash */
82 $em_dash = _x( '—', 'em dash' );
84 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
85 $default_no_texturize_shortcodes = array('code');
87 // if a plugin has provided an autocorrect array, use it
88 if ( isset($wp_cockneyreplace) ) {
89 $cockney = array_keys($wp_cockneyreplace);
90 $cockneyreplace = array_values($wp_cockneyreplace);
91 } elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
92 $cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
93 $cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
95 $cockney = $cockneyreplace = array();
98 $static_characters = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
99 $static_replacements = array_merge( array( '…', $opening_quote, $closing_quote, ' ™' ), $cockneyreplace );
102 // Pattern-based replacements of characters.
103 // Sort the remaining patterns into several arrays for performance tuning.
104 $dynamic_characters = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
105 $dynamic_replacements = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
107 $spaces = wp_spaces_regexp();
109 // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
110 if ( "'" !== $apos || "'" !== $closing_single_quote ) {
111 $dynamic[ '/\'(\d\d)\'(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $apos . '$1' . $closing_single_quote;
113 if ( "'" !== $apos || '"' !== $closing_quote ) {
114 $dynamic[ '/\'(\d\d)"(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $apos . '$1' . $closing_quote;
117 // '99 '99s '99's (apostrophe) But never '9 or '99% or '999 or '99.0.
118 if ( "'" !== $apos ) {
119 $dynamic[ '/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/' ] = $apos;
122 // Quoted Numbers like '0.42'
123 if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
124 $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $opening_single_quote . '$1' . $closing_single_quote;
127 // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
128 if ( "'" !== $opening_single_quote ) {
129 $dynamic[ '/(?<=\A|[([{"\-]|<|' . $spaces . ')\'/' ] = $opening_single_quote;
132 // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
133 if ( "'" !== $apos ) {
134 $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos;
138 if ( "'" !== $prime ) {
139 $dynamic[ '/(?<=\d)\'/' ] = $prime;
142 // Single quotes followed by spaces or ending punctuation.
143 if ( "'" !== $closing_single_quote ) {
144 $dynamic[ '/\'(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $closing_single_quote;
147 $dynamic_characters['apos'] = array_keys( $dynamic );
148 $dynamic_replacements['apos'] = array_values( $dynamic );
151 // Quoted Numbers like "42"
152 if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
153 $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $opening_quote . '$1' . $closing_quote;
157 if ( '"' !== $double_prime ) {
158 $dynamic[ '/(?<=\d)"/' ] = $double_prime;
161 // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
162 if ( '"' !== $opening_quote ) {
163 $dynamic[ '/(?<=\A|[([{\-]|<|' . $spaces . ')"(?!' . $spaces . ')/' ] = $opening_quote;
166 // Any remaining double quotes.
167 if ( '"' !== $closing_quote ) {
168 $dynamic[ '/"/' ] = $closing_quote;
171 $dynamic_characters['quote'] = array_keys( $dynamic );
172 $dynamic_replacements['quote'] = array_values( $dynamic );
176 $dynamic[ '/---/' ] = $em_dash;
177 $dynamic[ '/(?<=' . $spaces . ')--(?=' . $spaces . ')/' ] = $em_dash;
178 $dynamic[ '/(?<!xn)--/' ] = $en_dash;
179 $dynamic[ '/(?<=' . $spaces . ')-(?=' . $spaces . ')/' ] = $en_dash;
181 $dynamic_characters['dash'] = array_keys( $dynamic );
182 $dynamic_replacements['dash'] = array_values( $dynamic );
185 // Must do this every time in case plugins use these filters in a context sensitive manner
187 * Filter the list of HTML elements not to texturize.
191 * @param array $default_no_texturize_tags An array of HTML element names.
193 $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
195 * Filter the list of shortcodes not to texturize.
199 * @param array $default_no_texturize_shortcodes An array of shortcode names.
201 $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
203 $no_texturize_tags_stack = array();
204 $no_texturize_shortcodes_stack = array();
206 // Look for shortcodes and HTML elements.
208 $tagnames = array_keys( $shortcode_tags );
209 $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
210 $tagregexp = "(?:$tagregexp)(?![\\w-])"; // Excerpt of get_shortcode_regex().
213 '!' // Start of comment, after the <.
214 . '(?:' // Unroll the loop: Consume everything until --> is found.
215 . '-(?!->)' // Dash not followed by end of comment.
216 . '[^\-]*+' // Consume non-dashes.
217 . ')*+' // Loop possessively.
218 . '(?:-->)?'; // End of comment. If not found, match all input.
221 '\[' // Find start of shortcode.
222 . '[\/\[]?' // Shortcodes may begin with [/ or [[
223 . $tagregexp // Only match registered shortcodes, because performance.
225 . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
227 . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
228 . ')*+' // Possessive critical.
229 . '\]' // Find end of shortcode.
230 . '\]?'; // Shortcodes may end with ]]
233 '/(' // Capture the entire match.
234 . '<' // Find start of element.
235 . '(?(?=!--)' // Is this a comment?
236 . $comment_regex // Find end of comment.
238 . '[^>]+>' // Find end of element.
241 . $shortcode_regex // Find shortcodes.
244 $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
246 foreach ( $textarr as &$curl ) {
247 // Only call _wptexturize_pushpop_element if $curl is a delimiter.
249 if ( '<' === $first && '<!--' === substr( $curl, 0, 4 ) ) {
250 // This is an HTML comment delimeter.
254 } elseif ( '<' === $first && '>' === substr( $curl, -1 ) ) {
255 // This is an HTML element delimiter.
257 _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
259 } elseif ( '' === trim( $curl ) ) {
260 // This is a newline between delimiters. Performance improves when we check this.
264 } elseif ( '[' === $first && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
265 // This is a shortcode delimiter.
267 if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
268 // Looks like a normal shortcode.
269 _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
271 // Looks like an escaped shortcode.
275 } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
276 // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
278 $curl = str_replace( $static_characters, $static_replacements, $curl );
280 if ( false !== strpos( $curl, "'" ) ) {
281 $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
283 if ( false !== strpos( $curl, '"' ) ) {
284 $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
286 if ( false !== strpos( $curl, '-' ) ) {
287 $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
290 // 9x9 (times), but never 0x9999
291 if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
292 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
293 $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1×$2', $curl );
297 $text = implode( '', $textarr );
299 // Replace each & with & unless it already looks like an entity.
300 $text = preg_replace('/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $text);
306 * Search for disabled element tags. Push element to stack on tag open and pop
309 * Assumes first char of $text is tag opening and last char is tag closing.
310 * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
315 * @param string $text Text to check. Must be a tag like `<html>` or `[shortcode]`.
316 * @param array $stack List of open tag elements.
317 * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
319 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements) {
320 // Is it an opening tag or closing tag?
321 if ( '/' !== $text[1] ) {
324 } elseif ( 0 == count( $stack ) ) {
325 // Stack is empty. Just stop.
328 $opening_tag = false;
332 // Parse out the tag name.
333 $space = strpos( $text, ' ' );
334 if ( false === $space ) {
337 $space -= $name_offset;
339 $tag = substr( $text, $name_offset, $space );
341 // Handle disabled tags.
342 if ( in_array( $tag, $disabled_elements ) ) {
343 if ( $opening_tag ) {
345 * This disables texturize until we find a closing tag of our type
346 * (e.g. <pre>) even if there was invalid nesting before that
348 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
349 * "baba" won't be texturize
352 array_push( $stack, $tag );
353 } elseif ( end( $stack ) == $tag ) {
360 * Replaces double line-breaks with paragraph elements.
362 * A group of regex replaces used to identify text formatted with newlines and
363 * replace double line-breaks with HTML paragraph tags. The remaining
364 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
369 * @param string $pee The text which has to be formatted.
370 * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
371 * @return string Text which has been converted into correct paragraph tags.
373 function wpautop($pee, $br = true) {
376 if ( trim($pee) === '' )
379 $pee = $pee . "\n"; // just to make things a little easier, pad the end
381 if ( strpos($pee, '<pre') !== false ) {
382 $pee_parts = explode( '</pre>', $pee );
383 $last_pee = array_pop($pee_parts);
387 foreach ( $pee_parts as $pee_part ) {
388 $start = strpos($pee_part, '<pre');
391 if ( $start === false ) {
396 $name = "<pre wp-pre-tag-$i></pre>";
397 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
399 $pee .= substr( $pee_part, 0, $start ) . $name;
406 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
407 // Space things out a little
408 $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|legend|section|article|aside|hgroup|header|footer|nav|figure|details|menu|summary)';
409 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
410 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
411 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
413 if ( strpos( $pee, '<option' ) !== false ) {
414 // no P/BR around option
415 $pee = preg_replace( '|\s*<option|', '<option', $pee );
416 $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
419 if ( strpos( $pee, '</object>' ) !== false ) {
420 // no P/BR around param and embed
421 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
422 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
423 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
426 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
427 // no P/BR around source and track
428 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
429 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
430 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
433 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
434 // make paragraphs, including one at the end
435 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
438 foreach ( $pees as $tinkle ) {
439 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
442 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
443 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
444 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
445 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
446 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
447 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
448 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
449 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
452 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
453 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
454 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
457 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
458 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
459 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
461 if ( !empty($pre_tags) )
462 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
468 * Newline preservation help function for wpautop
473 * @param array $matches preg_replace_callback matches array
476 function _autop_newline_preservation_helper( $matches ) {
477 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
481 * Don't auto-p wrap shortcodes that stand alone
483 * Ensures that shortcodes are not wrapped in `<p>...</p>`.
487 * @param string $pee The content.
488 * @return string The filtered content.
490 function shortcode_unautop( $pee ) {
491 global $shortcode_tags;
493 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
497 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
498 $spaces = wp_spaces_regexp();
502 . '<p>' // Opening paragraph
503 . '(?:' . $spaces . ')*+' // Optional leading whitespace
504 . '(' // 1: The shortcode
505 . '\\[' // Opening bracket
506 . "($tagregexp)" // 2: Shortcode name
507 . '(?![\\w-])' // Not followed by word character or hyphen
508 // Unroll the loop: Inside the opening shortcode tag
509 . '[^\\]\\/]*' // Not a closing bracket or forward slash
511 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
512 . '[^\\]\\/]*' // Not a closing bracket or forward slash
515 . '\\/\\]' // Self closing tag and closing bracket
517 . '\\]' // Closing bracket
518 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
519 . '[^\\[]*+' // Not an opening bracket
521 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
522 . '[^\\[]*+' // Not an opening bracket
524 . '\\[\\/\\2\\]' // Closing shortcode tag
528 . '(?:' . $spaces . ')*+' // optional trailing whitespace
529 . '<\\/p>' // closing paragraph
532 return preg_replace( $pattern, '$1', $pee );
536 * Checks to see if a string is utf8 encoded.
538 * NOTE: This function checks for 5-Byte sequences, UTF8
539 * has Bytes Sequences with a maximum length of 4.
541 * @author bmorel at ssi dot fr (modified)
544 * @param string $str The string to be checked
545 * @return bool True if $str fits a UTF-8 model, false otherwise.
547 function seems_utf8($str) {
548 mbstring_binary_safe_encoding();
549 $length = strlen($str);
550 reset_mbstring_encoding();
551 for ($i=0; $i < $length; $i++) {
553 if ($c < 0x80) $n = 0; # 0bbbbbbb
554 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
555 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
556 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
557 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
558 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
559 else return false; # Does not match any model
560 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
561 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
569 * Converts a number of special characters into their HTML entities.
571 * Specifically deals with: &, <, >, ", and '.
573 * $quote_style can be set to ENT_COMPAT to encode " to
574 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
579 * @param string $string The text which is to be encoded.
580 * @param int $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.
581 * @param string $charset Optional. The character encoding of the string. Default is false.
582 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
583 * @return string The encoded text with HTML entities.
585 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
586 $string = (string) $string;
588 if ( 0 === strlen( $string ) )
591 // Don't bother if there are no specialchars - saves some processing
592 if ( ! preg_match( '/[&<>"\']/', $string ) )
595 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
596 if ( empty( $quote_style ) )
597 $quote_style = ENT_NOQUOTES;
598 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
599 $quote_style = ENT_QUOTES;
601 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
604 if ( ! isset( $_charset ) ) {
605 $alloptions = wp_load_alloptions();
606 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
608 $charset = $_charset;
611 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
614 $_quote_style = $quote_style;
616 if ( $quote_style === 'double' ) {
617 $quote_style = ENT_COMPAT;
618 $_quote_style = ENT_COMPAT;
619 } elseif ( $quote_style === 'single' ) {
620 $quote_style = ENT_NOQUOTES;
623 // Handle double encoding ourselves
624 if ( $double_encode ) {
625 $string = @htmlspecialchars( $string, $quote_style, $charset );
627 // Decode & into &
628 $string = wp_specialchars_decode( $string, $_quote_style );
630 // Guarantee every &entity; is valid or re-encode the &
631 $string = wp_kses_normalize_entities( $string );
633 // Now re-encode everything except &entity;
634 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
636 for ( $i = 0; $i < count( $string ); $i += 2 )
637 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
639 $string = implode( '', $string );
642 // Backwards compatibility
643 if ( 'single' === $_quote_style )
644 $string = str_replace( "'", ''', $string );
650 * Converts a number of HTML entities into their special characters.
652 * Specifically deals with: &, <, >, ", and '.
654 * $quote_style can be set to ENT_COMPAT to decode " entities,
655 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
659 * @param string $string The text which is to be decoded.
660 * @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.
661 * @return string The decoded text without HTML entities.
663 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
664 $string = (string) $string;
666 if ( 0 === strlen( $string ) ) {
670 // Don't bother if there are no entities - saves a lot of processing
671 if ( strpos( $string, '&' ) === false ) {
675 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
676 if ( empty( $quote_style ) ) {
677 $quote_style = ENT_NOQUOTES;
678 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
679 $quote_style = ENT_QUOTES;
682 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
683 $single = array( ''' => '\'', ''' => '\'' );
684 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
685 $double = array( '"' => '"', '"' => '"', '"' => '"' );
686 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
687 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
688 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
690 if ( $quote_style === ENT_QUOTES ) {
691 $translation = array_merge( $single, $double, $others );
692 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
693 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
694 $translation = array_merge( $double, $others );
695 $translation_preg = array_merge( $double_preg, $others_preg );
696 } elseif ( $quote_style === 'single' ) {
697 $translation = array_merge( $single, $others );
698 $translation_preg = array_merge( $single_preg, $others_preg );
699 } elseif ( $quote_style === ENT_NOQUOTES ) {
700 $translation = $others;
701 $translation_preg = $others_preg;
704 // Remove zero padding on numeric entities
705 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
707 // Replace characters according to translation table
708 return strtr( $string, $translation );
712 * Checks for invalid UTF8 in a string.
716 * @param string $string The text which is to be checked.
717 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
718 * @return string The checked text.
720 function wp_check_invalid_utf8( $string, $strip = false ) {
721 $string = (string) $string;
723 if ( 0 === strlen( $string ) ) {
727 // Store the site charset as a static to avoid multiple calls to get_option()
729 if ( !isset( $is_utf8 ) ) {
730 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
736 // Check for support for utf8 in the installed PCRE library once and store the result in a static
738 if ( !isset( $utf8_pcre ) ) {
739 $utf8_pcre = @preg_match( '/^./u', 'a' );
741 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
746 // preg_match fails when it encounters invalid UTF8 in $string
747 if ( 1 === @preg_match( '/^./us', $string ) ) {
751 // Attempt to strip the bad chars if requested (not recommended)
752 if ( $strip && function_exists( 'iconv' ) ) {
753 return iconv( 'utf-8', 'utf-8', $string );
760 * Encode the Unicode values to be used in the URI.
764 * @param string $utf8_string
765 * @param int $length Max length of the string
766 * @return string String with Unicode encoded for URI.
768 function utf8_uri_encode( $utf8_string, $length = 0 ) {
774 mbstring_binary_safe_encoding();
775 $string_length = strlen( $utf8_string );
776 reset_mbstring_encoding();
778 for ($i = 0; $i < $string_length; $i++ ) {
780 $value = ord( $utf8_string[ $i ] );
782 if ( $value < 128 ) {
783 if ( $length && ( $unicode_length >= $length ) )
785 $unicode .= chr($value);
788 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
792 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
794 if ( count( $values ) == $num_octets ) {
795 if ($num_octets == 3) {
796 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
797 $unicode_length += 9;
799 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
800 $unicode_length += 6;
813 * Converts all accent characters to ASCII characters.
815 * If there are no accent characters, then the string given is just returned.
819 * @param string $string Text that might have accent characters
820 * @return string Filtered string with replaced "nice" characters.
822 function remove_accents($string) {
823 if ( !preg_match('/[\x80-\xff]/', $string) )
826 if (seems_utf8($string)) {
828 // Decompositions for Latin-1 Supplement
829 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
830 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
831 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
832 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
833 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
834 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
835 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
836 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
837 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
838 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
839 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
840 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
841 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
842 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
843 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
844 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
845 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
846 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
847 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
848 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
849 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
850 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
851 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
852 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
853 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
854 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
855 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
856 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
857 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
858 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
859 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
860 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
861 // Decompositions for Latin Extended-A
862 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
863 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
864 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
865 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
866 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
867 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
868 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
869 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
870 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
871 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
872 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
873 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
874 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
875 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
876 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
877 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
878 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
879 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
880 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
881 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
882 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
883 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
884 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
885 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
886 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
887 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
888 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
889 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
890 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
891 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
892 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
893 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
894 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
895 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
896 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
897 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
898 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
899 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
900 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
901 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
902 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
903 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
904 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
905 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
906 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
907 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
908 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
909 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
910 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
911 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
912 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
913 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
914 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
915 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
916 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
917 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
918 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
919 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
920 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
921 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
922 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
923 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
924 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
925 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
926 // Decompositions for Latin Extended-B
927 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
928 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
930 chr(226).chr(130).chr(172) => 'E',
932 chr(194).chr(163) => '',
933 // Vowels with diacritic (Vietnamese)
935 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
936 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
938 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
939 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
940 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
941 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
942 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
943 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
944 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
946 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
947 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
948 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
949 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
950 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
951 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
952 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
953 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
954 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
955 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
956 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
957 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
959 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
960 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
961 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
962 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
963 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
964 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
965 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
966 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
968 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
969 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
970 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
971 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
972 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
973 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
975 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
976 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
977 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
978 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
979 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
980 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
981 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
982 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
983 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
984 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
985 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
986 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
987 // Vowels with diacritic (Chinese, Hanyu Pinyin)
988 chr(201).chr(145) => 'a',
990 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
992 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
994 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
995 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
996 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
997 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
998 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
1000 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
1003 // Used for locale-specific rules
1004 $locale = get_locale();
1006 if ( 'de_DE' == $locale ) {
1007 $chars[ chr(195).chr(132) ] = 'Ae';
1008 $chars[ chr(195).chr(164) ] = 'ae';
1009 $chars[ chr(195).chr(150) ] = 'Oe';
1010 $chars[ chr(195).chr(182) ] = 'oe';
1011 $chars[ chr(195).chr(156) ] = 'Ue';
1012 $chars[ chr(195).chr(188) ] = 'ue';
1013 $chars[ chr(195).chr(159) ] = 'ss';
1014 } elseif ( 'da_DK' === $locale ) {
1015 $chars[ chr(195).chr(134) ] = 'Ae';
1016 $chars[ chr(195).chr(166) ] = 'ae';
1017 $chars[ chr(195).chr(152) ] = 'Oe';
1018 $chars[ chr(195).chr(184) ] = 'oe';
1019 $chars[ chr(195).chr(133) ] = 'Aa';
1020 $chars[ chr(195).chr(165) ] = 'aa';
1023 $string = strtr($string, $chars);
1025 // Assume ISO-8859-1 if not UTF-8
1026 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1027 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1028 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1029 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1030 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1031 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1032 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1033 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1034 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1035 .chr(252).chr(253).chr(255);
1037 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1039 $string = strtr($string, $chars['in'], $chars['out']);
1040 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1041 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1042 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1049 * Sanitizes a filename, replacing whitespace with dashes.
1051 * Removes special characters that are illegal in filenames on certain
1052 * operating systems and special characters requiring special escaping
1053 * to manipulate at the command line. Replaces spaces and consecutive
1054 * dashes with a single dash. Trims period, dash and underscore from beginning
1055 * and end of filename.
1059 * @param string $filename The filename to be sanitized
1060 * @return string The sanitized filename
1062 function sanitize_file_name( $filename ) {
1063 $filename_raw = $filename;
1064 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1066 * Filter the list of characters to remove from a filename.
1070 * @param array $special_chars Characters to remove.
1071 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1073 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1074 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1075 $filename = str_replace( $special_chars, '', $filename );
1076 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1077 $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
1078 $filename = trim( $filename, '.-_' );
1080 // Split the filename into a base and extension[s]
1081 $parts = explode('.', $filename);
1083 // Return if only one extension
1084 if ( count( $parts ) <= 2 ) {
1086 * Filter a sanitized filename string.
1090 * @param string $filename Sanitized filename.
1091 * @param string $filename_raw The filename prior to sanitization.
1093 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1096 // Process multiple extensions
1097 $filename = array_shift($parts);
1098 $extension = array_pop($parts);
1099 $mimes = get_allowed_mime_types();
1102 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1103 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1105 foreach ( (array) $parts as $part) {
1106 $filename .= '.' . $part;
1108 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1110 foreach ( $mimes as $ext_preg => $mime_match ) {
1111 $ext_preg = '!^(' . $ext_preg . ')$!i';
1112 if ( preg_match( $ext_preg, $part ) ) {
1121 $filename .= '.' . $extension;
1122 /** This filter is documented in wp-includes/formatting.php */
1123 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1127 * Sanitizes a username, stripping out unsafe characters.
1129 * Removes tags, octets, entities, and if strict is enabled, will only keep
1130 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1131 * raw username (the username in the parameter), and the value of $strict as
1132 * parameters for the 'sanitize_user' filter.
1136 * @param string $username The username to be sanitized.
1137 * @param bool $strict If set limits $username to specific characters. Default false.
1138 * @return string The sanitized username, after passing through filters.
1140 function sanitize_user( $username, $strict = false ) {
1141 $raw_username = $username;
1142 $username = wp_strip_all_tags( $username );
1143 $username = remove_accents( $username );
1145 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1146 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1148 // If strict, reduce to ASCII for max portability.
1150 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1152 $username = trim( $username );
1153 // Consolidate contiguous whitespace
1154 $username = preg_replace( '|\s+|', ' ', $username );
1157 * Filter a sanitized username string.
1161 * @param string $username Sanitized username.
1162 * @param string $raw_username The username prior to sanitization.
1163 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1165 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1169 * Sanitizes a string key.
1171 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1175 * @param string $key String key
1176 * @return string Sanitized key
1178 function sanitize_key( $key ) {
1180 $key = strtolower( $key );
1181 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1184 * Filter a sanitized key string.
1188 * @param string $key Sanitized key.
1189 * @param string $raw_key The key prior to sanitization.
1191 return apply_filters( 'sanitize_key', $key, $raw_key );
1195 * Sanitizes a title, or returns a fallback title.
1197 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1198 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1203 * @param string $title The string to be sanitized.
1204 * @param string $fallback_title Optional. A title to use if $title is empty.
1205 * @param string $context Optional. The operation for which the string is sanitized
1206 * @return string The sanitized string.
1208 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1209 $raw_title = $title;
1211 if ( 'save' == $context )
1212 $title = remove_accents($title);
1215 * Filter a sanitized title string.
1219 * @param string $title Sanitized title.
1220 * @param string $raw_title The title prior to sanitization.
1221 * @param string $context The context for which the title is being sanitized.
1223 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1225 if ( '' === $title || false === $title )
1226 $title = $fallback_title;
1232 * Sanitizes a title with the 'query' context.
1234 * Used for querying the database for a value from URL.
1238 * @param string $title The string to be sanitized.
1239 * @return string The sanitized string.
1241 function sanitize_title_for_query( $title ) {
1242 return sanitize_title( $title, '', 'query' );
1246 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1248 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1249 * Whitespace becomes a dash.
1253 * @param string $title The title to be sanitized.
1254 * @param string $raw_title Optional. Not used.
1255 * @param string $context Optional. The operation for which the string is sanitized.
1256 * @return string The sanitized title.
1258 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1259 $title = strip_tags($title);
1260 // Preserve escaped octets.
1261 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1262 // Remove percent signs that are not part of an octet.
1263 $title = str_replace('%', '', $title);
1265 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1267 if (seems_utf8($title)) {
1268 if (function_exists('mb_strtolower')) {
1269 $title = mb_strtolower($title, 'UTF-8');
1271 $title = utf8_uri_encode($title, 200);
1274 $title = strtolower($title);
1275 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1276 $title = str_replace('.', '-', $title);
1278 if ( 'save' == $context ) {
1279 // Convert nbsp, ndash and mdash to hyphens
1280 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1282 // Strip these characters entirely
1283 $title = str_replace( array(
1287 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1289 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1290 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1291 // copy, reg, deg, hellip and trade
1292 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1294 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1295 // grave accent, macron, caron
1296 '%cc%80', '%cc%84', '%cc%8c',
1299 // Convert times to x
1300 $title = str_replace( '%c3%97', 'x', $title );
1303 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1304 $title = preg_replace('/\s+/', '-', $title);
1305 $title = preg_replace('|-+|', '-', $title);
1306 $title = trim($title, '-');
1312 * Ensures a string is a valid SQL 'order by' clause.
1314 * Accepts one or more columns, with or without a sort order (ASC / DESC).
1315 * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
1317 * Also accepts 'RAND()'.
1321 * @param string $orderby Order by clause to be validated.
1322 * @return string|bool Returns $orderby if valid, false otherwise.
1324 function sanitize_sql_orderby( $orderby ) {
1325 if ( preg_match( '/^\s*(([a-z0-9_]+|`[a-z0-9_]+`)(\s+(ASC|DESC))?\s*(,\s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^\s*RAND\(\s*\)\s*$/i', $orderby ) ) {
1332 * Sanitizes an HTML classname to ensure it only contains valid characters.
1334 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1335 * string then it will return the alternative value supplied.
1337 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1341 * @param string $class The classname to be sanitized
1342 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1343 * Defaults to an empty string.
1344 * @return string The sanitized value
1346 function sanitize_html_class( $class, $fallback = '' ) {
1347 //Strip out any % encoded octets
1348 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1350 //Limit to A-Z,a-z,0-9,_,-
1351 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1353 if ( '' == $sanitized )
1354 $sanitized = $fallback;
1357 * Filter a sanitized HTML class string.
1361 * @param string $sanitized The sanitized HTML class.
1362 * @param string $class HTML class before sanitization.
1363 * @param string $fallback The fallback string.
1365 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1369 * Converts a number of characters from a string.
1371 * Metadata tags `<title>` and `<category>` are removed, `<br>` and `<hr>` are
1372 * converted into correct XHTML and Unicode characters are converted to the
1377 * @param string $content String of characters to be converted.
1378 * @param string $deprecated Not used.
1379 * @return string Converted string.
1381 function convert_chars($content, $deprecated = '') {
1382 if ( !empty( $deprecated ) )
1383 _deprecated_argument( __FUNCTION__, '0.71' );
1385 // Translation of invalid Unicode references range to valid range
1386 $wp_htmltranswinuni = array(
1387 '€' => '€', // the Euro sign
1389 '‚' => '‚', // these are Windows CP1252 specific characters
1390 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1391 '„' => '„',
1392 '…' => '…',
1393 '†' => '†',
1394 '‡' => '‡',
1395 'ˆ' => 'ˆ',
1396 '‰' => '‰',
1397 'Š' => 'Š',
1398 '‹' => '‹',
1399 'Œ' => 'Œ',
1401 'Ž' => 'Ž',
1404 '‘' => '‘',
1405 '’' => '’',
1406 '“' => '“',
1407 '”' => '”',
1408 '•' => '•',
1409 '–' => '–',
1410 '—' => '—',
1411 '˜' => '˜',
1412 '™' => '™',
1413 'š' => 'š',
1414 '›' => '›',
1415 'œ' => 'œ',
1417 'ž' => 'ž',
1418 'Ÿ' => 'Ÿ'
1421 // Remove metadata tags
1422 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1423 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1425 // Converts lone & characters into & (a.k.a. &)
1426 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1429 $content = strtr($content, $wp_htmltranswinuni);
1431 // Just a little XHTML help
1432 $content = str_replace('<br>', '<br />', $content);
1433 $content = str_replace('<hr>', '<hr />', $content);
1439 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1443 * @param string $text Text to be balanced
1444 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1445 * @return string Balanced text
1447 function balanceTags( $text, $force = false ) {
1448 if ( $force || get_option('use_balanceTags') == 1 ) {
1449 return force_balance_tags( $text );
1456 * Balances tags of string using a modified stack.
1460 * @author Leonard Lin <leonard@acm.org>
1462 * @copyright November 4, 2001
1464 * @todo Make better - change loop condition to $text in 1.2
1465 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1466 * 1.1 Fixed handling of append/stack pop order of end text
1467 * Added Cleaning Hooks
1470 * @param string $text Text to be balanced.
1471 * @return string Balanced text.
1473 function force_balance_tags( $text ) {
1474 $tagstack = array();
1478 // Known single-entity/self-closing tags
1479 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1480 // Tags that can be immediately nested within themselves
1481 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1483 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1484 $text = str_replace('< !--', '< !--', $text);
1485 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1486 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1488 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1489 $newtext .= $tagqueue;
1491 $i = strpos($text, $regex[0]);
1492 $l = strlen($regex[0]);
1494 // clear the shifter
1497 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1498 $tag = strtolower(substr($regex[1],1));
1499 // if too many closing tags
1500 if( $stacksize <= 0 ) {
1502 // or close to be safe $tag = '/' . $tag;
1504 // if stacktop value = tag close value then pop
1505 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1506 $tag = '</' . $tag . '>'; // Close Tag
1508 array_pop( $tagstack );
1510 } else { // closing tag not at top, search for it
1511 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1512 if ( $tagstack[$j] == $tag ) {
1513 // add tag to tagqueue
1514 for ( $k = $stacksize-1; $k >= $j; $k--) {
1515 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1523 } else { // Begin Tag
1524 $tag = strtolower($regex[1]);
1528 // If it's an empty tag "< >", do nothing
1532 // ElseIf it presents itself as a self-closing tag...
1533 elseif ( substr( $regex[2], -1 ) == '/' ) {
1534 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1535 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1536 if ( ! in_array( $tag, $single_tags ) )
1537 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1539 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1540 elseif ( in_array($tag, $single_tags) ) {
1543 // Else it's not a single-entity tag
1545 // If the top of the stack is the same as the tag we want to push, close previous tag
1546 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1547 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1550 $stacksize = array_push( $tagstack, $tag );
1554 $attributes = $regex[2];
1555 if( ! empty( $attributes ) && $attributes[0] != '>' )
1556 $attributes = ' ' . $attributes;
1558 $tag = '<' . $tag . $attributes . '>';
1559 //If already queuing a close tag, then put this tag on, too
1560 if ( !empty($tagqueue) ) {
1565 $newtext .= substr($text, 0, $i) . $tag;
1566 $text = substr($text, $i + $l);
1570 $newtext .= $tagqueue;
1572 // Add Remaining text
1576 while( $x = array_pop($tagstack) )
1577 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1579 // WP fix for the bug with HTML comments
1580 $newtext = str_replace("< !--","<!--",$newtext);
1581 $newtext = str_replace("< !--","< !--",$newtext);
1587 * Acts on text which is about to be edited.
1589 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1590 * to convert special characters to HTML entities. If $richedit is set to true,
1591 * it is simply a holder for the 'format_to_edit' filter.
1595 * @param string $content The text about to be edited.
1596 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1597 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1599 function format_to_edit( $content, $richedit = false ) {
1601 * Filter the text to be formatted for editing.
1605 * @param string $content The text, prior to formatting for editing.
1607 $content = apply_filters( 'format_to_edit', $content );
1609 $content = esc_textarea( $content );
1614 * Add leading zeros when necessary.
1616 * If you set the threshold to '4' and the number is '10', then you will get
1617 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1618 * will get back '5000'.
1620 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1621 * and the size of the number. If the number is large enough, then no zeros will
1626 * @param mixed $number Number to append zeros to if not greater than threshold.
1627 * @param int $threshold Digit places number needs to be to not have zeros added.
1628 * @return string Adds leading zeros to number if needed.
1630 function zeroise($number, $threshold) {
1631 return sprintf('%0'.$threshold.'s', $number);
1635 * Adds backslashes before letters and before a number at the start of a string.
1639 * @param string $string Value to which backslashes will be added.
1640 * @return string String with backslashes inserted.
1642 function backslashit($string) {
1643 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1644 $string = '\\\\' . $string;
1645 return addcslashes( $string, 'A..Za..z' );
1649 * Appends a trailing slash.
1651 * Will remove trailing forward and backslashes if it exists already before adding
1652 * a trailing forward slash. This prevents double slashing a string or path.
1654 * The primary use of this is for paths and thus should be used for paths. It is
1655 * not restricted to paths and offers no specific path support.
1659 * @param string $string What to add the trailing slash to.
1660 * @return string String with trailing slash added.
1662 function trailingslashit( $string ) {
1663 return untrailingslashit( $string ) . '/';
1667 * Removes trailing forward slashes and backslashes if they exist.
1669 * The primary use of this is for paths and thus should be used for paths. It is
1670 * not restricted to paths and offers no specific path support.
1674 * @param string $string What to remove the trailing slashes from.
1675 * @return string String without the trailing slashes.
1677 function untrailingslashit( $string ) {
1678 return rtrim( $string, '/\\' );
1682 * Adds slashes to escape strings.
1684 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1685 * http://www.php.net/magic_quotes} for more details.
1689 * @param string $gpc The string returned from HTTP request data.
1690 * @return string Returns a string escaped with slashes.
1692 function addslashes_gpc($gpc) {
1693 if ( get_magic_quotes_gpc() )
1694 $gpc = stripslashes($gpc);
1696 return wp_slash($gpc);
1700 * Navigates through an array and removes slashes from the values.
1702 * If an array is passed, the array_map() function causes a callback to pass the
1703 * value back to the function. The slashes from this value will removed.
1707 * @param mixed $value The value to be stripped.
1708 * @return mixed Stripped value.
1710 function stripslashes_deep($value) {
1711 if ( is_array($value) ) {
1712 $value = array_map('stripslashes_deep', $value);
1713 } elseif ( is_object($value) ) {
1714 $vars = get_object_vars( $value );
1715 foreach ($vars as $key=>$data) {
1716 $value->{$key} = stripslashes_deep( $data );
1718 } elseif ( is_string( $value ) ) {
1719 $value = stripslashes($value);
1726 * Navigates through an array and encodes the values to be used in a URL.
1731 * @param array|string $value The array or string to be encoded.
1732 * @return array|string $value The encoded array (or string from the callback).
1734 function urlencode_deep($value) {
1735 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1740 * Navigates through an array and raw encodes the values to be used in a URL.
1744 * @param array|string $value The array or string to be encoded.
1745 * @return array|string $value The encoded array (or string from the callback).
1747 function rawurlencode_deep( $value ) {
1748 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1752 * Converts email addresses characters to HTML entities to block spam bots.
1756 * @param string $email_address Email address.
1757 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
1758 * @return string Converted email address.
1760 function antispambot( $email_address, $hex_encoding = 0 ) {
1761 $email_no_spam_address = '';
1762 for ( $i = 0; $i < strlen( $email_address ); $i++ ) {
1763 $j = rand( 0, 1 + $hex_encoding );
1765 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
1766 } elseif ( $j == 1 ) {
1767 $email_no_spam_address .= $email_address[$i];
1768 } elseif ( $j == 2 ) {
1769 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
1773 $email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
1775 return $email_no_spam_address;
1779 * Callback to convert URI match to HTML A element.
1781 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1782 * make_clickable()}.
1787 * @param array $matches Single Regex Match.
1788 * @return string HTML A element with URI address.
1790 function _make_url_clickable_cb($matches) {
1793 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1794 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1795 // Then we can let the parenthesis balancer do its thing below.
1796 $url .= $matches[3];
1799 $suffix = $matches[3];
1802 // Include parentheses in the URL only if paired
1803 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1804 $suffix = strrchr( $url, ')' ) . $suffix;
1805 $url = substr( $url, 0, strrpos( $url, ')' ) );
1808 $url = esc_url($url);
1812 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1816 * Callback to convert URL match to HTML A element.
1818 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1819 * make_clickable()}.
1824 * @param array $matches Single Regex Match.
1825 * @return string HTML A element with URL address.
1827 function _make_web_ftp_clickable_cb($matches) {
1829 $dest = $matches[2];
1830 $dest = 'http://' . $dest;
1831 $dest = esc_url($dest);
1835 // removed trailing [.,;:)] from URL
1836 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1837 $ret = substr($dest, -1);
1838 $dest = substr($dest, 0, strlen($dest)-1);
1840 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1844 * Callback to convert email address match to HTML A element.
1846 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1847 * make_clickable()}.
1852 * @param array $matches Single Regex Match.
1853 * @return string HTML A element with email address.
1855 function _make_email_clickable_cb($matches) {
1856 $email = $matches[2] . '@' . $matches[3];
1857 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1861 * Convert plaintext URI to HTML links.
1863 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1868 * @param string $text Content to convert URIs.
1869 * @return string Content with converted URIs.
1871 function make_clickable( $text ) {
1873 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
1874 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
1875 foreach ( $textarr as $piece ) {
1877 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
1879 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
1882 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
1887 // Long strings might contain expensive edge cases ...
1888 if ( 10000 < strlen( $piece ) ) {
1890 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
1891 if ( 2101 < strlen( $chunk ) ) {
1892 $r .= $chunk; // Too big, no whitespace: bail.
1894 $r .= make_clickable( $chunk );
1898 $ret = " $piece "; // Pad with whitespace to simplify the regexes
1901 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
1903 [\\w]{1,20}+:// # Scheme and hier-part prefix
1904 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
1905 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
1906 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
1907 [\'.,;:!?)] # Punctuation URL character
1908 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
1911 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
1912 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
1913 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
1915 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
1917 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
1918 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
1920 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
1925 // Cleanup of accidental links within links
1926 $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
1931 * Breaks a string into chunks by splitting at whitespace characters.
1932 * The length of each returned chunk is as close to the specified length goal as possible,
1933 * with the caveat that each chunk includes its trailing delimiter.
1934 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
1936 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
1938 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
1940 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
1942 * 0 => '1234 67890 ', // 11 characters: Perfect split
1943 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
1944 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
1945 * 3 => '1234 890 ', // 11 characters: Perfect split
1946 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
1947 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
1948 * 6 => ' 45678 ', // 11 characters: Perfect split
1949 * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
1955 * @param string $string The string to split.
1956 * @param int $goal The desired chunk length.
1957 * @return array Numeric array of chunks.
1959 function _split_str_by_whitespace( $string, $goal ) {
1962 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
1964 while ( $goal < strlen( $string_nullspace ) ) {
1965 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
1967 if ( false === $pos ) {
1968 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
1969 if ( false === $pos ) {
1974 $chunks[] = substr( $string, 0, $pos + 1 );
1975 $string = substr( $string, $pos + 1 );
1976 $string_nullspace = substr( $string_nullspace, $pos + 1 );
1980 $chunks[] = $string;
1987 * Adds rel nofollow string to all HTML A elements in content.
1991 * @param string $text Content that may contain HTML A elements.
1992 * @return string Converted content.
1994 function wp_rel_nofollow( $text ) {
1995 // This is a pre save filter, so text is already escaped.
1996 $text = stripslashes($text);
1997 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1998 $text = wp_slash($text);
2003 * Callback to add rel=nofollow string to HTML A element.
2005 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2006 * string to prevent from invalidating (X)HTML.
2010 * @param array $matches Single Match
2011 * @return string HTML A Element with rel nofollow.
2013 function wp_rel_nofollow_callback( $matches ) {
2014 $text = $matches[1];
2015 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
2016 return "<a $text rel=\"nofollow\">";
2020 * Convert one smiley code to the icon graphic file equivalent.
2022 * Callback handler for {@link convert_smilies()}.
2023 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2024 * `<img>` string for that smiley.
2026 * @global array $wpsmiliestrans
2029 * @param array $matches Single match. Smiley code to convert to image.
2030 * @return string Image string for smiley.
2032 function translate_smiley( $matches ) {
2033 global $wpsmiliestrans;
2035 if ( count( $matches ) == 0 )
2038 $smiley = trim( reset( $matches ) );
2039 $img = $wpsmiliestrans[ $smiley ];
2042 * Filter the Smiley image URL before it's used in the image element.
2046 * @param string $smiley_url URL for the smiley image.
2047 * @param string $img Filename for the smiley image.
2048 * @param string $site_url Site URL, as returned by site_url().
2050 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2052 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" />', esc_url( $src_url ), esc_attr( $smiley ) );
2056 * Convert text equivalent of smilies to images.
2058 * Will only convert smilies if the option 'use_smilies' is true and the global
2059 * used in the function isn't empty.
2062 * @uses $wp_smiliessearch
2064 * @param string $text Content to convert smilies from text.
2065 * @return string Converted content with text smilies replaced with images.
2067 function convert_smilies( $text ) {
2068 global $wp_smiliessearch;
2070 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2071 // HTML loop taken from texturize function, could possible be consolidated
2072 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2073 $stop = count( $textarr );// loop stuff
2075 // Ignore proessing of specific tags
2076 $tags_to_ignore = 'code|pre|style|script|textarea';
2077 $ignore_block_element = '';
2079 for ( $i = 0; $i < $stop; $i++ ) {
2080 $content = $textarr[$i];
2082 // If we're in an ignore block, wait until we find its closing tag
2083 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2084 $ignore_block_element = $matches[1];
2087 // If it's not a tag and not in ignore block
2088 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2089 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2092 // did we exit ignore block
2093 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2094 $ignore_block_element = '';
2097 $output .= $content;
2100 // return default text.
2107 * Verifies that an email is valid.
2109 * Does not grok i18n domains. Not RFC compliant.
2113 * @param string $email Email address to verify.
2114 * @param boolean $deprecated Deprecated.
2115 * @return string|bool Either false or the valid email address.
2117 function is_email( $email, $deprecated = false ) {
2118 if ( ! empty( $deprecated ) )
2119 _deprecated_argument( __FUNCTION__, '3.0' );
2121 // Test for the minimum length the email can be
2122 if ( strlen( $email ) < 3 ) {
2124 * Filter whether an email address is valid.
2126 * This filter is evaluated under several different contexts, such as 'email_too_short',
2127 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2128 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2132 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2133 * @param string $email The email address being checked.
2134 * @param string $message An explanatory message to the user.
2135 * @param string $context Context under which the email was tested.
2137 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2140 // Test for an @ character after the first position
2141 if ( strpos( $email, '@', 1 ) === false ) {
2142 /** This filter is documented in wp-includes/formatting.php */
2143 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2146 // Split out the local and domain parts
2147 list( $local, $domain ) = explode( '@', $email, 2 );
2150 // Test for invalid characters
2151 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2152 /** This filter is documented in wp-includes/formatting.php */
2153 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2157 // Test for sequences of periods
2158 if ( preg_match( '/\.{2,}/', $domain ) ) {
2159 /** This filter is documented in wp-includes/formatting.php */
2160 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2163 // Test for leading and trailing periods and whitespace
2164 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2165 /** This filter is documented in wp-includes/formatting.php */
2166 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2169 // Split the domain into subs
2170 $subs = explode( '.', $domain );
2172 // Assume the domain will have at least two subs
2173 if ( 2 > count( $subs ) ) {
2174 /** This filter is documented in wp-includes/formatting.php */
2175 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2178 // Loop through each sub
2179 foreach ( $subs as $sub ) {
2180 // Test for leading and trailing hyphens and whitespace
2181 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2182 /** This filter is documented in wp-includes/formatting.php */
2183 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2186 // Test for invalid characters
2187 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2188 /** This filter is documented in wp-includes/formatting.php */
2189 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2193 // Congratulations your email made it!
2194 /** This filter is documented in wp-includes/formatting.php */
2195 return apply_filters( 'is_email', $email, $email, null );
2199 * Convert to ASCII from email subjects.
2203 * @param string $string Subject line
2204 * @return string Converted string to ASCII
2206 function wp_iso_descrambler($string) {
2207 /* this may only work with iso-8859-1, I'm afraid */
2208 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2211 $subject = str_replace('_', ' ', $matches[2]);
2212 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
2218 * Helper function to convert hex encoded chars to ASCII
2223 * @param array $match The preg_replace_callback matches array
2224 * @return string Converted chars
2226 function _wp_iso_convert( $match ) {
2227 return chr( hexdec( strtolower( $match[1] ) ) );
2231 * Returns a date in the GMT equivalent.
2233 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2234 * timezone_string available, the date is assumed to be in that timezone,
2235 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2236 * format can be overridden using the $format parameter.
2240 * @param string $string The date to be converted.
2241 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2242 * @return string GMT version of the date provided.
2244 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2245 $tz = get_option( 'timezone_string' );
2247 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2249 return gmdate( $format, 0 );
2250 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2251 $string_gmt = $datetime->format( $format );
2253 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 ) )
2254 return gmdate( $format, 0 );
2255 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2256 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2262 * Converts a GMT date into the correct format for the blog.
2264 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2265 * timezone_string available, the returned date is in that timezone, otherwise
2266 * it simply adds the value of gmt_offset. Return format can be overridden
2267 * using the $format parameter
2271 * @param string $string The date to be converted.
2272 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2273 * @return string Formatted date relative to the timezone / GMT offset.
2275 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2276 $tz = get_option( 'timezone_string' );
2278 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2280 return date( $format, 0 );
2281 $datetime->setTimezone( new DateTimeZone( $tz ) );
2282 $string_localtime = $datetime->format( $format );
2284 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) )
2285 return date( $format, 0 );
2286 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2287 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2289 return $string_localtime;
2293 * Computes an offset in seconds from an iso8601 timezone.
2297 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2298 * @return int|float The offset in seconds.
2300 function iso8601_timezone_to_offset($timezone) {
2301 // $timezone is either 'Z' or '[+|-]hhmm'
2302 if ($timezone == 'Z') {
2305 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2306 $hours = intval(substr($timezone, 1, 2));
2307 $minutes = intval(substr($timezone, 3, 4)) / 60;
2308 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2314 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2318 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2319 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2320 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2322 function iso8601_to_datetime($date_string, $timezone = 'user') {
2323 $timezone = strtolower($timezone);
2325 if ($timezone == 'gmt') {
2327 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);
2329 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2330 $offset = iso8601_timezone_to_offset($date_bits[7]);
2331 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2332 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2335 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2336 $timestamp -= $offset;
2338 return gmdate('Y-m-d H:i:s', $timestamp);
2340 } else if ($timezone == 'user') {
2341 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);
2346 * Adds a element attributes to open links in new windows.
2348 * Comment text in popup windows should be filtered through this. Right now it's
2349 * a moderately dumb function, ideally it would detect whether a target or rel
2350 * attribute was already there and adjust its actions accordingly.
2354 * @param string $text Content to replace links to open in a new window.
2355 * @return string Content that has filtered links.
2357 function popuplinks($text) {
2358 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2363 * Strips out all characters that are not allowable in an email.
2367 * @param string $email Email address to filter.
2368 * @return string Filtered email address.
2370 function sanitize_email( $email ) {
2371 // Test for the minimum length the email can be
2372 if ( strlen( $email ) < 3 ) {
2374 * Filter a sanitized email address.
2376 * This filter is evaluated under several contexts, including 'email_too_short',
2377 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2378 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2382 * @param string $email The sanitized email address.
2383 * @param string $email The email address, as provided to sanitize_email().
2384 * @param string $message A message to pass to the user.
2386 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2389 // Test for an @ character after the first position
2390 if ( strpos( $email, '@', 1 ) === false ) {
2391 /** This filter is documented in wp-includes/formatting.php */
2392 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2395 // Split out the local and domain parts
2396 list( $local, $domain ) = explode( '@', $email, 2 );
2399 // Test for invalid characters
2400 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2401 if ( '' === $local ) {
2402 /** This filter is documented in wp-includes/formatting.php */
2403 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2407 // Test for sequences of periods
2408 $domain = preg_replace( '/\.{2,}/', '', $domain );
2409 if ( '' === $domain ) {
2410 /** This filter is documented in wp-includes/formatting.php */
2411 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2414 // Test for leading and trailing periods and whitespace
2415 $domain = trim( $domain, " \t\n\r\0\x0B." );
2416 if ( '' === $domain ) {
2417 /** This filter is documented in wp-includes/formatting.php */
2418 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2421 // Split the domain into subs
2422 $subs = explode( '.', $domain );
2424 // Assume the domain will have at least two subs
2425 if ( 2 > count( $subs ) ) {
2426 /** This filter is documented in wp-includes/formatting.php */
2427 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2430 // Create an array that will contain valid subs
2431 $new_subs = array();
2433 // Loop through each sub
2434 foreach ( $subs as $sub ) {
2435 // Test for leading and trailing hyphens
2436 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2438 // Test for invalid characters
2439 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2441 // If there's anything left, add it to the valid subs
2442 if ( '' !== $sub ) {
2447 // If there aren't 2 or more valid subs
2448 if ( 2 > count( $new_subs ) ) {
2449 /** This filter is documented in wp-includes/formatting.php */
2450 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2453 // Join valid subs into the new domain
2454 $domain = join( '.', $new_subs );
2456 // Put the email back together
2457 $email = $local . '@' . $domain;
2459 // Congratulations your email made it!
2460 /** This filter is documented in wp-includes/formatting.php */
2461 return apply_filters( 'sanitize_email', $email, $email, null );
2465 * Determines the difference between two timestamps.
2467 * The difference is returned in a human readable format such as "1 hour",
2468 * "5 mins", "2 days".
2472 * @param int $from Unix timestamp from which the difference begins.
2473 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2474 * @return string Human readable time difference.
2476 function human_time_diff( $from, $to = '' ) {
2477 if ( empty( $to ) ) {
2481 $diff = (int) abs( $to - $from );
2483 if ( $diff < HOUR_IN_SECONDS ) {
2484 $mins = round( $diff / MINUTE_IN_SECONDS );
2487 /* translators: min=minute */
2488 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2489 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2490 $hours = round( $diff / HOUR_IN_SECONDS );
2493 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2494 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2495 $days = round( $diff / DAY_IN_SECONDS );
2498 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2499 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2500 $weeks = round( $diff / WEEK_IN_SECONDS );
2503 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2504 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2505 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2508 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2509 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2510 $years = round( $diff / YEAR_IN_SECONDS );
2513 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2517 * Filter the human readable difference between two timestamps.
2521 * @param string $since The difference in human readable text.
2522 * @param int $diff The difference in seconds.
2523 * @param int $from Unix timestamp from which the difference begins.
2524 * @param int $to Unix timestamp to end the time difference.
2526 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2530 * Generates an excerpt from the content, if needed.
2532 * The excerpt word amount will be 55 words and if the amount is greater than
2533 * that, then the string ' […]' will be appended to the excerpt. If the string
2534 * is less than 55 words, then the content will be returned as is.
2536 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2537 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2541 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2542 * @return string The excerpt.
2544 function wp_trim_excerpt($text = '') {
2545 $raw_excerpt = $text;
2546 if ( '' == $text ) {
2547 $text = get_the_content('');
2549 $text = strip_shortcodes( $text );
2551 /** This filter is documented in wp-includes/post-template.php */
2552 $text = apply_filters( 'the_content', $text );
2553 $text = str_replace(']]>', ']]>', $text);
2556 * Filter the number of words in an excerpt.
2560 * @param int $number The number of words. Default 55.
2562 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2564 * Filter the string in the "more" link displayed after a trimmed excerpt.
2568 * @param string $more_string The string shown within the more link.
2570 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2571 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2574 * Filter the trimmed excerpt string.
2578 * @param string $text The trimmed text.
2579 * @param string $raw_excerpt The text prior to trimming.
2581 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2585 * Trims text to a certain number of words.
2587 * This function is localized. For languages that count 'words' by the individual
2588 * character (such as East Asian languages), the $num_words argument will apply
2589 * to the number of individual characters.
2593 * @param string $text Text to trim.
2594 * @param int $num_words Number of words. Default 55.
2595 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2596 * @return string Trimmed text.
2598 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2599 if ( null === $more )
2600 $more = __( '…' );
2601 $original_text = $text;
2602 $text = wp_strip_all_tags( $text );
2603 /* translators: If your word count is based on single characters (East Asian characters),
2604 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2605 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2606 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2607 preg_match_all( '/./u', $text, $words_array );
2608 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2611 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2614 if ( count( $words_array ) > $num_words ) {
2615 array_pop( $words_array );
2616 $text = implode( $sep, $words_array );
2617 $text = $text . $more;
2619 $text = implode( $sep, $words_array );
2622 * Filter the text content after words have been trimmed.
2626 * @param string $text The trimmed text.
2627 * @param int $num_words The number of words to trim the text to. Default 5.
2628 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2629 * @param string $original_text The text before it was trimmed.
2631 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2635 * Converts named entities into numbered entities.
2639 * @param string $text The text within which entities will be converted.
2640 * @return string Text with converted entities.
2642 function ent2ncr($text) {
2645 * Filter text before named entities are converted into numbered entities.
2647 * A non-null string must be returned for the filter to be evaluated.
2651 * @param null $converted_text The text to be converted. Default null.
2652 * @param string $text The text prior to entity conversion.
2654 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2655 if( null !== $filtered )
2659 '"' => '"',
2664 ' ' => ' ',
2665 '¡' => '¡',
2666 '¢' => '¢',
2667 '£' => '£',
2668 '¤' => '¤',
2669 '¥' => '¥',
2670 '¦' => '¦',
2671 '&brkbar;' => '¦',
2672 '§' => '§',
2673 '¨' => '¨',
2674 '¨' => '¨',
2675 '©' => '©',
2676 'ª' => 'ª',
2677 '«' => '«',
2678 '¬' => '¬',
2679 '­' => '­',
2680 '®' => '®',
2681 '¯' => '¯',
2682 '&hibar;' => '¯',
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 'œ' => 'œ',
2765 'Š' => 'Š',
2766 'š' => 'š',
2767 'Ÿ' => 'Ÿ',
2768 'ƒ' => 'ƒ',
2769 'ˆ' => 'ˆ',
2770 '˜' => '˜',
2771 'Α' => 'Α',
2772 'Β' => 'Β',
2773 'Γ' => 'Γ',
2774 'Δ' => 'Δ',
2775 'Ε' => 'Ε',
2776 'Ζ' => 'Ζ',
2777 'Η' => 'Η',
2778 'Θ' => 'Θ',
2779 'Ι' => 'Ι',
2780 'Κ' => 'Κ',
2781 'Λ' => 'Λ',
2785 'Ο' => 'Ο',
2787 'Ρ' => 'Ρ',
2788 'Σ' => 'Σ',
2789 'Τ' => 'Τ',
2790 'Υ' => 'Υ',
2791 'Φ' => 'Φ',
2792 'Χ' => 'Χ',
2793 'Ψ' => 'Ψ',
2794 'Ω' => 'Ω',
2795 'α' => 'α',
2796 'β' => 'β',
2797 'γ' => 'γ',
2798 'δ' => 'δ',
2799 'ε' => 'ε',
2800 'ζ' => 'ζ',
2801 'η' => 'η',
2802 'θ' => 'θ',
2803 'ι' => 'ι',
2804 'κ' => 'κ',
2805 'λ' => 'λ',
2809 'ο' => 'ο',
2811 'ρ' => 'ρ',
2812 'ς' => 'ς',
2813 'σ' => 'σ',
2814 'τ' => 'τ',
2815 'υ' => 'υ',
2816 'φ' => 'φ',
2817 'χ' => 'χ',
2818 'ψ' => 'ψ',
2819 'ω' => 'ω',
2820 'ϑ' => 'ϑ',
2821 'ϒ' => 'ϒ',
2822 'ϖ' => 'ϖ',
2823 ' ' => ' ',
2824 ' ' => ' ',
2825 ' ' => ' ',
2826 '‌' => '‌',
2827 '‍' => '‍',
2828 '‎' => '‎',
2829 '‏' => '‏',
2830 '–' => '–',
2831 '—' => '—',
2832 '‘' => '‘',
2833 '’' => '’',
2834 '‚' => '‚',
2835 '“' => '“',
2836 '”' => '”',
2837 '„' => '„',
2838 '†' => '†',
2839 '‡' => '‡',
2840 '•' => '•',
2841 '…' => '…',
2842 '‰' => '‰',
2843 '′' => '′',
2844 '″' => '″',
2845 '‹' => '‹',
2846 '›' => '›',
2847 '‾' => '‾',
2848 '⁄' => '⁄',
2849 '€' => '€',
2850 'ℑ' => 'ℑ',
2851 '℘' => '℘',
2852 'ℜ' => 'ℜ',
2853 '™' => '™',
2854 'ℵ' => 'ℵ',
2855 '↵' => '↵',
2856 '⇐' => '⇐',
2857 '⇑' => '⇑',
2858 '⇒' => '⇒',
2859 '⇓' => '⇓',
2860 '⇔' => '⇔',
2861 '∀' => '∀',
2862 '∂' => '∂',
2863 '∃' => '∃',
2864 '∅' => '∅',
2865 '∇' => '∇',
2866 '∈' => '∈',
2867 '∉' => '∉',
2868 '∋' => '∋',
2869 '∏' => '∏',
2870 '∑' => '∑',
2871 '−' => '−',
2872 '∗' => '∗',
2873 '√' => '√',
2874 '∝' => '∝',
2875 '∞' => '∞',
2876 '∠' => '∠',
2877 '∧' => '∧',
2878 '∨' => '∨',
2879 '∩' => '∩',
2880 '∪' => '∪',
2881 '∫' => '∫',
2882 '∴' => '∴',
2883 '∼' => '∼',
2884 '≅' => '≅',
2885 '≈' => '≈',
2886 '≠' => '≠',
2887 '≡' => '≡',
2888 '≤' => '≤',
2889 '≥' => '≥',
2890 '⊂' => '⊂',
2891 '⊃' => '⊃',
2892 '⊄' => '⊄',
2893 '⊆' => '⊆',
2894 '⊇' => '⊇',
2895 '⊕' => '⊕',
2896 '⊗' => '⊗',
2897 '⊥' => '⊥',
2898 '⋅' => '⋅',
2899 '⌈' => '⌈',
2900 '⌉' => '⌉',
2901 '⌊' => '⌊',
2902 '⌋' => '⌋',
2903 '⟨' => '〈',
2904 '⟩' => '〉',
2905 '←' => '←',
2906 '↑' => '↑',
2907 '→' => '→',
2908 '↓' => '↓',
2909 '↔' => '↔',
2910 '◊' => '◊',
2911 '♠' => '♠',
2912 '♣' => '♣',
2913 '♥' => '♥',
2914 '♦' => '♦'
2917 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2921 * Formats text for the rich text editor.
2923 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2924 * be applied to an empty string.
2928 * @param string $text The text to be formatted.
2929 * @return string The formatted text after filter is applied.
2931 function wp_richedit_pre($text) {
2932 if ( empty( $text ) ) {
2934 * Filter text returned for the rich text editor.
2936 * This filter is first evaluated, and the value returned, if an empty string
2937 * is passed to wp_richedit_pre(). If an empty string is passed, it results
2938 * in a break tag and line feed.
2940 * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
2941 * return after being formatted.
2945 * @param string $output Text for the rich text editor.
2947 return apply_filters( 'richedit_pre', '' );
2950 $output = convert_chars($text);
2951 $output = wpautop($output);
2952 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
2954 /** This filter is documented in wp-includes/formatting.php */
2955 return apply_filters( 'richedit_pre', $output );
2959 * Formats text for the HTML editor.
2961 * Unless $output is empty it will pass through htmlspecialchars before the
2962 * 'htmledit_pre' filter is applied.
2966 * @param string $output The text to be formatted.
2967 * @return string Formatted text after filter applied.
2969 function wp_htmledit_pre($output) {
2970 if ( !empty($output) )
2971 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
2974 * Filter the text before it is formatted for the HTML editor.
2978 * @param string $output The HTML-formatted text.
2980 return apply_filters( 'htmledit_pre', $output );
2984 * Perform a deep string replace operation to ensure the values in $search are no longer present
2986 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2987 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2988 * str_replace would return
2993 * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
2994 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
2995 * @return string The string with the replaced svalues.
2997 function _deep_replace( $search, $subject ) {
2998 $subject = (string) $subject;
3002 $subject = str_replace( $search, '', $subject, $count );
3009 * Escapes data for use in a MySQL query.
3011 * Usually you should prepare queries using wpdb::prepare().
3012 * Sometimes, spot-escaping is required or useful. One example
3013 * is preparing an array for use in an IN clause.
3016 * @param string|array $data Unescaped data
3017 * @return string|array Escaped data
3019 function esc_sql( $data ) {
3021 return $wpdb->_escape( $data );
3025 * Checks and cleans a URL.
3027 * A number of characters are removed from the URL. If the URL is for displaying
3028 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3029 * is applied to the returned cleaned URL.
3033 * @param string $url The URL to be cleaned.
3034 * @param array $protocols Optional. An array of acceptable protocols.
3035 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
3036 * @param string $_context Private. Use esc_url_raw() for database usage.
3037 * @return string The cleaned $url after the 'clean_url' filter is applied.
3039 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3040 $original_url = $url;
3044 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3045 $strip = array('%0d', '%0a', '%0D', '%0A');
3046 $url = _deep_replace($strip, $url);
3047 $url = str_replace(';//', '://', $url);
3048 /* If the URL doesn't appear to contain a scheme, we
3049 * presume it needs http:// appended (unless a relative
3050 * link starting with /, # or ? or a php file).
3052 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3053 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3054 $url = 'http://' . $url;
3056 // Replace ampersands and single quotes only when displaying.
3057 if ( 'display' == $_context ) {
3058 $url = wp_kses_normalize_entities( $url );
3059 $url = str_replace( '&', '&', $url );
3060 $url = str_replace( "'", ''', $url );
3063 if ( '/' === $url[0] ) {
3064 $good_protocol_url = $url;
3066 if ( ! is_array( $protocols ) )
3067 $protocols = wp_allowed_protocols();
3068 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3069 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3074 * Filter a string cleaned and escaped for output as a URL.
3078 * @param string $good_protocol_url The cleaned URL to be returned.
3079 * @param string $original_url The URL prior to cleaning.
3080 * @param string $_context If 'display', replace ampersands and single quotes only.
3082 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3086 * Performs esc_url() for database usage.
3090 * @param string $url The URL to be cleaned.
3091 * @param array $protocols An array of acceptable protocols.
3092 * @return string The cleaned URL.
3094 function esc_url_raw( $url, $protocols = null ) {
3095 return esc_url( $url, $protocols, 'db' );
3099 * Convert entities, while preserving already-encoded entities.
3101 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3105 * @param string $myHTML The text to be converted.
3106 * @return string Converted text.
3108 function htmlentities2($myHTML) {
3109 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3110 $translation_table[chr(38)] = '&';
3111 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3115 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3117 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3118 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3119 * be in single quotes. The filter 'js_escape' is also applied here.
3123 * @param string $text The text to be escaped.
3124 * @return string Escaped text.
3126 function esc_js( $text ) {
3127 $safe_text = wp_check_invalid_utf8( $text );
3128 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3129 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3130 $safe_text = str_replace( "\r", '', $safe_text );
3131 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3133 * Filter a string cleaned and escaped for output in JavaScript.
3135 * Text passed to esc_js() is stripped of invalid or special characters,
3136 * and properly slashed for output.
3140 * @param string $safe_text The text after it has been escaped.
3141 * @param string $text The text prior to being escaped.
3143 return apply_filters( 'js_escape', $safe_text, $text );
3147 * Escaping for HTML blocks.
3151 * @param string $text
3154 function esc_html( $text ) {
3155 $safe_text = wp_check_invalid_utf8( $text );
3156 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3158 * Filter a string cleaned and escaped for output in HTML.
3160 * Text passed to esc_html() is stripped of invalid or special characters
3165 * @param string $safe_text The text after it has been escaped.
3166 * @param string $text The text prior to being escaped.
3168 return apply_filters( 'esc_html', $safe_text, $text );
3172 * Escaping for HTML attributes.
3176 * @param string $text
3179 function esc_attr( $text ) {
3180 $safe_text = wp_check_invalid_utf8( $text );
3181 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3183 * Filter a string cleaned and escaped for output in an HTML attribute.
3185 * Text passed to esc_attr() is stripped of invalid or special characters
3190 * @param string $safe_text The text after it has been escaped.
3191 * @param string $text The text prior to being escaped.
3193 return apply_filters( 'attribute_escape', $safe_text, $text );
3197 * Escaping for textarea values.
3201 * @param string $text
3204 function esc_textarea( $text ) {
3205 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3207 * Filter a string cleaned and escaped for output in a textarea element.
3211 * @param string $safe_text The text after it has been escaped.
3212 * @param string $text The text prior to being escaped.
3214 return apply_filters( 'esc_textarea', $safe_text, $text );
3218 * Escape an HTML tag name.
3222 * @param string $tag_name
3225 function tag_escape($tag_name) {
3226 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3228 * Filter a string cleaned and escaped for output as an HTML tag.
3232 * @param string $safe_tag The tag name after it has been escaped.
3233 * @param string $tag_name The text before it was escaped.
3235 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3239 * Convert full URL paths to absolute paths.
3241 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3242 * beginning, so it isn't a true relative link, but from the web root base.
3245 * @since 4.1.0 Support was added for relative URLs.
3247 * @param string $link Full URL path.
3248 * @return string Absolute path.
3250 function wp_make_link_relative( $link ) {
3251 return preg_replace( '|^(https?:)?//[^/]+(/.*)|i', '$2', $link );
3255 * Sanitises various option values based on the nature of the option.
3257 * This is basically a switch statement which will pass $value through a number
3258 * of functions depending on the $option.
3262 * @param string $option The name of the option.
3263 * @param string $value The unsanitised value.
3264 * @return string Sanitized value.
3266 function sanitize_option($option, $value) {
3268 switch ( $option ) {
3269 case 'admin_email' :
3270 case 'new_admin_email' :
3271 $value = sanitize_email( $value );
3272 if ( ! is_email( $value ) ) {
3273 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3274 if ( function_exists( 'add_settings_error' ) )
3275 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.' ) );
3279 case 'thumbnail_size_w':
3280 case 'thumbnail_size_h':
3281 case 'medium_size_w':
3282 case 'medium_size_h':
3283 case 'large_size_w':
3284 case 'large_size_h':
3285 case 'mailserver_port':
3286 case 'comment_max_links':
3287 case 'page_on_front':
3288 case 'page_for_posts':
3289 case 'rss_excerpt_length':
3290 case 'default_category':
3291 case 'default_email_category':
3292 case 'default_link_category':
3293 case 'close_comments_days_old':
3294 case 'comments_per_page':
3295 case 'thread_comments_depth':
3296 case 'users_can_register':
3297 case 'start_of_week':
3298 $value = absint( $value );
3301 case 'posts_per_page':
3302 case 'posts_per_rss':
3303 $value = (int) $value;
3304 if ( empty($value) )
3307 $value = abs($value);
3310 case 'default_ping_status':
3311 case 'default_comment_status':
3312 // Options that if not there have 0 value but need to be something like "closed"
3313 if ( $value == '0' || $value == '')
3317 case 'blogdescription':
3319 $value = wp_kses_post( $value );
3320 $value = esc_html( $value );
3323 case 'blog_charset':
3324 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3328 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3329 if ( null === $value )
3332 $value = intval( $value );
3337 case 'mailserver_url':
3338 case 'mailserver_login':
3339 case 'mailserver_pass':
3341 $value = strip_tags( $value );
3342 $value = wp_kses_data( $value );
3346 $value = explode( "\n", $value );
3347 $value = array_filter( array_map( 'trim', $value ) );
3348 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3349 $value = implode( "\n", $value );
3353 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3357 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3358 $value = esc_url_raw($value);
3360 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3361 if ( function_exists('add_settings_error') )
3362 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3367 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3368 $value = esc_url_raw($value);
3370 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3371 if ( function_exists('add_settings_error') )
3372 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3377 $allowed = get_available_languages();
3378 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3379 $allowed[] = WPLANG;
3381 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3382 $value = get_option( $option );
3386 case 'illegal_names':
3387 if ( ! is_array( $value ) )
3388 $value = explode( ' ', $value );
3390 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3396 case 'limited_email_domains':
3397 case 'banned_email_domains':
3398 if ( ! is_array( $value ) )
3399 $value = explode( "\n", $value );
3401 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3404 foreach ( $domains as $domain ) {
3405 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
3412 case 'timezone_string':
3413 $allowed_zones = timezone_identifiers_list();
3414 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3415 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3416 if ( function_exists('add_settings_error') )
3417 add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
3421 case 'permalink_structure':
3422 case 'category_base':
3424 $value = esc_url_raw( $value );
3425 $value = str_replace( 'http://', '', $value );
3428 case 'default_role' :
3429 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3430 $value = 'subscriber';
3433 case 'moderation_keys':
3434 case 'blacklist_keys':
3435 $value = explode( "\n", $value );
3436 $value = array_filter( array_map( 'trim', $value ) );
3437 $value = array_unique( $value );
3438 $value = implode( "\n", $value );
3443 * Filter an option value following sanitization.
3447 * @param string $value The sanitized option value.
3448 * @param string $option The option name.
3450 $value = apply_filters( "sanitize_option_{$option}", $value, $option );
3456 * Parses a string into variables to be stored in an array.
3458 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3459 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3463 * @param string $string The string to be parsed.
3464 * @param array $array Variables will be stored in this array.
3466 function wp_parse_str( $string, &$array ) {
3467 parse_str( $string, $array );
3468 if ( get_magic_quotes_gpc() )
3469 $array = stripslashes_deep( $array );
3471 * Filter the array of variables derived from a parsed string.
3475 * @param array $array The array populated with variables.
3477 $array = apply_filters( 'wp_parse_str', $array );
3481 * Convert lone less than signs.
3483 * KSES already converts lone greater than signs.
3487 * @param string $text Text to be converted.
3488 * @return string Converted text.
3490 function wp_pre_kses_less_than( $text ) {
3491 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3495 * Callback function used by preg_replace.
3499 * @param array $matches Populated by matches to preg_replace.
3500 * @return string The text returned after esc_html if needed.
3502 function wp_pre_kses_less_than_callback( $matches ) {
3503 if ( false === strpos($matches[0], '>') )
3504 return esc_html($matches[0]);
3509 * WordPress implementation of PHP sprintf() with filters.
3512 * @link http://www.php.net/sprintf
3514 * @param string $pattern The string which formatted args are inserted.
3515 * @param mixed $args,... Arguments to be formatted into the $pattern string.
3516 * @return string The formatted string.
3518 function wp_sprintf( $pattern ) {
3519 $args = func_get_args();
3520 $len = strlen($pattern);
3524 while ( $len > $start ) {
3525 // Last character: append and break
3526 if ( strlen($pattern) - 1 == $start ) {
3527 $result .= substr($pattern, -1);
3531 // Literal %: append and continue
3532 if ( substr($pattern, $start, 2) == '%%' ) {
3538 // Get fragment before next %
3539 $end = strpos($pattern, '%', $start + 1);
3540 if ( false === $end )
3542 $fragment = substr($pattern, $start, $end - $start);
3544 // Fragment has a specifier
3545 if ( $pattern[$start] == '%' ) {
3546 // Find numbered arguments or take the next one in order
3547 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3548 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3549 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3552 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3556 * Filter a fragment from the pattern passed to wp_sprintf().
3558 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3562 * @param string $fragment A fragment from the pattern.
3563 * @param string $arg The argument.
3565 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3566 if ( $_fragment != $fragment )
3567 $fragment = $_fragment;
3569 $fragment = sprintf($fragment, strval($arg) );
3572 // Append to result and move to next fragment
3573 $result .= $fragment;
3580 * Localize list items before the rest of the content.
3582 * The '%l' must be at the first characters can then contain the rest of the
3583 * content. The list items will have ', ', ', and', and ' and ' added depending
3584 * on the amount of list items in the $args parameter.
3588 * @param string $pattern Content containing '%l' at the beginning.
3589 * @param array $args List items to prepend to the content and replace '%l'.
3590 * @return string Localized list items and rest of the content.
3592 function wp_sprintf_l($pattern, $args) {
3594 if ( substr($pattern, 0, 2) != '%l' )
3597 // Nothing to work with
3602 * Filter the translated delimiters used by wp_sprintf_l().
3603 * Placeholders (%s) are included to assist translators and then
3604 * removed before the array of strings reaches the filter.
3606 * Please note: Ampersands and entities should be avoided here.
3610 * @param array $delimiters An array of translated delimiters.
3612 $l = apply_filters( 'wp_sprintf_l', array(
3613 /* translators: used to join items in a list with more than 2 items */
3614 'between' => sprintf( __('%s, %s'), '', '' ),
3615 /* translators: used to join last two items in a list with more than 2 times */
3616 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3617 /* translators: used to join items in a list with only 2 items */
3618 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3621 $args = (array) $args;
3622 $result = array_shift($args);
3623 if ( count($args) == 1 )
3624 $result .= $l['between_only_two'] . array_shift($args);
3625 // Loop when more than two args
3628 $arg = array_shift($args);
3631 $result .= $l['between_last_two'] . $arg;
3633 $result .= $l['between'] . $arg;
3635 return $result . substr($pattern, 2);
3639 * Safely extracts not more than the first $count characters from html string.
3641 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3642 * be counted as one character. For example & will be counted as 4, < as
3647 * @param string $str String to get the excerpt from.
3648 * @param integer $count Maximum number of characters to take.
3649 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3650 * @return string The excerpt.
3652 function wp_html_excerpt( $str, $count, $more = null ) {
3653 if ( null === $more )
3655 $str = wp_strip_all_tags( $str, true );
3656 $excerpt = mb_substr( $str, 0, $count );
3657 // remove part of an entity at the end
3658 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3659 if ( $str != $excerpt )
3660 $excerpt = trim( $excerpt ) . $more;
3665 * Add a Base url to relative links in passed content.
3667 * By default it supports the 'src' and 'href' attributes. However this can be
3668 * changed via the 3rd param.
3672 * @param string $content String to search for links in.
3673 * @param string $base The base URL to prefix to links.
3674 * @param array $attrs The attributes which should be processed.
3675 * @return string The processed content.
3677 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3678 global $_links_add_base;
3679 $_links_add_base = $base;
3680 $attrs = implode('|', (array)$attrs);
3681 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3685 * Callback to add a base url to relative links in passed content.
3690 * @param string $m The matched link.
3691 * @return string The processed link.
3693 function _links_add_base($m) {
3694 global $_links_add_base;
3695 //1 = attribute name 2 = quotation mark 3 = URL
3696 return $m[1] . '=' . $m[2] .
3697 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3699 WP_HTTP::make_absolute_url( $m[3], $_links_add_base )
3705 * Adds a Target attribute to all links in passed content.
3707 * This function by default only applies to `<a>` tags, however this can be
3708 * modified by the 3rd param.
3710 * *NOTE:* Any current target attributed will be stripped and replaced.
3714 * @param string $content String to search for links in.
3715 * @param string $target The Target to add to the links.
3716 * @param array $tags An array of tags to apply to.
3717 * @return string The processed content.
3719 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3720 global $_links_add_target;
3721 $_links_add_target = $target;
3722 $tags = implode('|', (array)$tags);
3723 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
3727 * Callback to add a target attribute to all links in passed content.
3732 * @param string $m The matched link.
3733 * @return string The processed link.
3735 function _links_add_target( $m ) {
3736 global $_links_add_target;
3738 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
3739 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3743 * Normalize EOL characters and strip duplicate whitespace.
3747 * @param string $str The string to normalize.
3748 * @return string The normalized string.
3750 function normalize_whitespace( $str ) {
3751 $str = trim( $str );
3752 $str = str_replace( "\r", "\n", $str );
3753 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3758 * Properly strip all HTML tags including script and style
3760 * This differs from strip_tags() because it removes the contents of
3761 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
3762 * will return 'something'. wp_strip_all_tags will return ''
3766 * @param string $string String containing HTML tags
3767 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3768 * @return string The processed string.
3770 function wp_strip_all_tags($string, $remove_breaks = false) {
3771 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3772 $string = strip_tags($string);
3774 if ( $remove_breaks )
3775 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3777 return trim( $string );
3781 * Sanitize a string from user input or from the db
3783 * check for invalid UTF-8,
3784 * Convert single < characters to entity,
3786 * remove line breaks, tabs and extra white space,
3791 * @param string $str
3794 function sanitize_text_field($str) {
3795 $filtered = wp_check_invalid_utf8( $str );
3797 if ( strpos($filtered, '<') !== false ) {
3798 $filtered = wp_pre_kses_less_than( $filtered );
3799 // This will strip extra whitespace for us.
3800 $filtered = wp_strip_all_tags( $filtered, true );
3802 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
3806 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
3807 $filtered = str_replace($match[0], '', $filtered);
3812 // Strip out the whitespace that may now exist after removing the octets.
3813 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
3817 * Filter a sanitized text field string.
3821 * @param string $filtered The sanitized string.
3822 * @param string $str The string prior to being sanitized.
3824 return apply_filters( 'sanitize_text_field', $filtered, $str );
3828 * i18n friendly version of basename()
3832 * @param string $path A path.
3833 * @param string $suffix If the filename ends in suffix this will also be cut off.
3836 function wp_basename( $path, $suffix = '' ) {
3837 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
3841 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
3843 * Violating our coding standards for a good function name.
3847 function capital_P_dangit( $text ) {
3848 // Simple replacement for titles
3849 $current_filter = current_filter();
3850 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
3851 return str_replace( 'Wordpress', 'WordPress', $text );
3852 // Still here? Use the more judicious replacement
3853 static $dblq = false;
3854 if ( false === $dblq )
3855 $dblq = _x( '“', 'opening curly double quote' );
3857 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
3858 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
3864 * Sanitize a mime type
3868 * @param string $mime_type Mime type
3869 * @return string Sanitized mime type
3871 function sanitize_mime_type( $mime_type ) {
3872 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3874 * Filter a mime type following sanitization.
3878 * @param string $sani_mime_type The sanitized mime type.
3879 * @param string $mime_type The mime type prior to sanitization.
3881 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
3885 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
3889 * @param string $to_ping Space or carriage return separated URLs
3890 * @return string URLs starting with the http or https protocol, separated by a carriage return.
3892 function sanitize_trackback_urls( $to_ping ) {
3893 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
3894 foreach ( $urls_to_ping as $k => $url ) {
3895 if ( !preg_match( '#^https?://.#i', $url ) )
3896 unset( $urls_to_ping[$k] );
3898 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
3899 $urls_to_ping = implode( "\n", $urls_to_ping );
3901 * Filter a list of trackback URLs following sanitization.
3903 * The string returned here consists of a space or carriage return-delimited list
3904 * of trackback URLs.
3908 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
3909 * @param string $to_ping Space or carriage return separated URLs before sanitization.
3911 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
3915 * Add slashes to a string or array of strings.
3917 * This should be used when preparing data for core API that expects slashed data.
3918 * This should not be used to escape data going directly into an SQL query.
3922 * @param string|array $value String or array of strings to slash.
3923 * @return string|array Slashed $value
3925 function wp_slash( $value ) {
3926 if ( is_array( $value ) ) {
3927 foreach ( $value as $k => $v ) {
3928 if ( is_array( $v ) ) {
3929 $value[$k] = wp_slash( $v );
3931 $value[$k] = addslashes( $v );
3935 $value = addslashes( $value );
3942 * Remove slashes from a string or array of strings.
3944 * This should be used to remove slashes from data passed to core API that
3945 * expects data to be unslashed.
3949 * @param string|array $value String or array of strings to unslash.
3950 * @return string|array Unslashed $value
3952 function wp_unslash( $value ) {
3953 return stripslashes_deep( $value );
3957 * Extract and return the first URL from passed content.
3961 * @param string $content A string which might contain a URL.
3962 * @return string The found URL.
3964 function get_url_in_content( $content ) {
3965 if ( empty( $content ) ) {
3969 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
3970 return esc_url_raw( $matches[2] );
3977 * Returns the regexp for common whitespace characters.
3979 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
3980 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
3981 * sequence was found to be unreliable due to random inclusion of the A0 byte.
3985 * @return string The spaces regexp.
3987 function wp_spaces_regexp() {
3990 if ( empty( $spaces ) ) {
3992 * Filter the regexp for common whitespace characters.
3994 * This string is substituted for the \s sequence as needed in regular
3995 * expressions. For websites not written in English, different characters
3996 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
3997 * sequence may not be in use.
4001 * @param string $spaces Regexp pattern for matching common whitespace characters.
4003 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );