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;
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 $regex = '/(' // Capture the entire match.
209 . '<' // Find start of element.
210 . '(?(?=!--)' // Is this a comment?
211 . '.+?--\s*>' // Find end of comment
213 . '[^>]+>' // Find end of element
216 . '\[' // Find start of shortcode.
217 . '\[?' // Shortcodes may begin with [[
219 . '[^\[\]<>]' // Shortcodes do not contain other shortcodes.
221 . '<[^>]+>' // HTML elements permitted. Prevents matching ] before >.
223 . '\]' // Find end of shortcode.
224 . '\]?' // Shortcodes may end with ]]
227 $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
229 foreach ( $textarr as &$curl ) {
230 // Only call _wptexturize_pushpop_element if $curl is a delimiter.
232 if ( '<' === $first && '>' === substr( $curl, -1 ) ) {
233 // This is an HTML delimiter.
235 if ( '<!--' !== substr( $curl, 0, 4 ) ) {
236 _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
239 } elseif ( '' === trim( $curl ) ) {
240 // This is a newline between delimiters. Performance improves when we check this.
244 } elseif ( '[' === $first && 1 === preg_match( '/^\[(?:[^\[\]<>]|<[^>]+>)++\]$/', $curl ) ) {
245 // This is a shortcode delimiter.
247 _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
249 } elseif ( '[' === $first && 1 === preg_match( '/^\[\[?(?:[^\[\]<>]|<[^>]+>)++\]\]?$/', $curl ) ) {
250 // This is an escaped shortcode delimiter.
253 // Do not push to the shortcodes stack.
257 } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
258 // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
260 $curl = str_replace( $static_characters, $static_replacements, $curl );
262 if ( false !== strpos( $curl, "'" ) ) {
263 $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
265 if ( false !== strpos( $curl, '"' ) ) {
266 $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
268 if ( false !== strpos( $curl, '-' ) ) {
269 $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
272 // 9x9 (times), but never 0x9999
273 if ( 1 === preg_match( '/(?<=\d)x-?\d/', $curl ) ) {
274 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
275 $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(-?\d[\d\.,]*)\b/', '$1×$2', $curl );
279 $text = implode( '', $textarr );
281 // Replace each & with & unless it already looks like an entity.
282 $text = preg_replace('/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $text);
288 * Search for disabled element tags. Push element to stack on tag open and pop
291 * Assumes first char of $text is tag opening and last char is tag closing.
292 * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
297 * @param string $text Text to check. Must be a tag like <html> or [shortcode].
298 * @param array $stack List of open tag elements.
299 * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
301 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements) {
302 // Is it an opening tag or closing tag?
303 if ( '/' !== $text[1] ) {
306 } elseif ( 0 == count( $stack ) ) {
307 // Stack is empty. Just stop.
310 $opening_tag = false;
314 // Parse out the tag name.
315 $space = strpos( $text, ' ' );
316 if ( FALSE === $space ) {
319 $space -= $name_offset;
321 $tag = substr( $text, $name_offset, $space );
323 // Handle disabled tags.
324 if ( in_array( $tag, $disabled_elements ) ) {
325 if ( $opening_tag ) {
327 * This disables texturize until we find a closing tag of our type
328 * (e.g. <pre>) even if there was invalid nesting before that
330 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
331 * "baba" won't be texturize
334 array_push( $stack, $tag );
335 } elseif ( end( $stack ) == $tag ) {
342 * Replaces double line-breaks with paragraph elements.
344 * A group of regex replaces used to identify text formatted with newlines and
345 * replace double line-breaks with HTML paragraph tags. The remaining
346 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
351 * @param string $pee The text which has to be formatted.
352 * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
353 * @return string Text which has been converted into correct paragraph tags.
355 function wpautop($pee, $br = true) {
358 if ( trim($pee) === '' )
361 $pee = $pee . "\n"; // just to make things a little easier, pad the end
363 if ( strpos($pee, '<pre') !== false ) {
364 $pee_parts = explode( '</pre>', $pee );
365 $last_pee = array_pop($pee_parts);
369 foreach ( $pee_parts as $pee_part ) {
370 $start = strpos($pee_part, '<pre');
373 if ( $start === false ) {
378 $name = "<pre wp-pre-tag-$i></pre>";
379 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
381 $pee .= substr( $pee_part, 0, $start ) . $name;
388 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
389 // Space things out a little
390 $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)';
391 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
392 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
393 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
395 if ( strpos( $pee, '<option' ) !== false ) {
396 // no P/BR around option
397 $pee = preg_replace( '|\s*<option|', '<option', $pee );
398 $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
401 if ( strpos( $pee, '</object>' ) !== false ) {
402 // no P/BR around param and embed
403 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
404 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
405 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
408 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
409 // no P/BR around source and track
410 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
411 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
412 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
415 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
416 // make paragraphs, including one at the end
417 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
420 foreach ( $pees as $tinkle ) {
421 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
424 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
425 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
426 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
427 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
428 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
429 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
430 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
431 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
434 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
435 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
436 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
439 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
440 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
441 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
443 if ( !empty($pre_tags) )
444 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
450 * Newline preservation help function for wpautop
455 * @param array $matches preg_replace_callback matches array
458 function _autop_newline_preservation_helper( $matches ) {
459 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
463 * Don't auto-p wrap shortcodes that stand alone
465 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
469 * @param string $pee The content.
470 * @return string The filtered content.
472 function shortcode_unautop( $pee ) {
473 global $shortcode_tags;
475 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
479 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
480 $spaces = wp_spaces_regexp();
484 . '<p>' // Opening paragraph
485 . '(?:' . $spaces . ')*+' // Optional leading whitespace
486 . '(' // 1: The shortcode
487 . '\\[' // Opening bracket
488 . "($tagregexp)" // 2: Shortcode name
489 . '(?![\\w-])' // Not followed by word character or hyphen
490 // Unroll the loop: Inside the opening shortcode tag
491 . '[^\\]\\/]*' // Not a closing bracket or forward slash
493 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
494 . '[^\\]\\/]*' // Not a closing bracket or forward slash
497 . '\\/\\]' // Self closing tag and closing bracket
499 . '\\]' // Closing bracket
500 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
501 . '[^\\[]*+' // Not an opening bracket
503 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
504 . '[^\\[]*+' // Not an opening bracket
506 . '\\[\\/\\2\\]' // Closing shortcode tag
510 . '(?:' . $spaces . ')*+' // optional trailing whitespace
511 . '<\\/p>' // closing paragraph
514 return preg_replace( $pattern, '$1', $pee );
518 * Checks to see if a string is utf8 encoded.
520 * NOTE: This function checks for 5-Byte sequences, UTF8
521 * has Bytes Sequences with a maximum length of 4.
523 * @author bmorel at ssi dot fr (modified)
526 * @param string $str The string to be checked
527 * @return bool True if $str fits a UTF-8 model, false otherwise.
529 function seems_utf8($str) {
530 mbstring_binary_safe_encoding();
531 $length = strlen($str);
532 reset_mbstring_encoding();
533 for ($i=0; $i < $length; $i++) {
535 if ($c < 0x80) $n = 0; # 0bbbbbbb
536 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
537 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
538 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
539 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
540 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
541 else return false; # Does not match any model
542 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
543 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
551 * Converts a number of special characters into their HTML entities.
553 * Specifically deals with: &, <, >, ", and '.
555 * $quote_style can be set to ENT_COMPAT to encode " to
556 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
561 * @param string $string The text which is to be encoded.
562 * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
563 * @param string $charset Optional. The character encoding of the string. Default is false.
564 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
565 * @return string The encoded text with HTML entities.
567 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
568 $string = (string) $string;
570 if ( 0 === strlen( $string ) )
573 // Don't bother if there are no specialchars - saves some processing
574 if ( ! preg_match( '/[&<>"\']/', $string ) )
577 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
578 if ( empty( $quote_style ) )
579 $quote_style = ENT_NOQUOTES;
580 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
581 $quote_style = ENT_QUOTES;
583 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
586 if ( ! isset( $_charset ) ) {
587 $alloptions = wp_load_alloptions();
588 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
590 $charset = $_charset;
593 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
596 $_quote_style = $quote_style;
598 if ( $quote_style === 'double' ) {
599 $quote_style = ENT_COMPAT;
600 $_quote_style = ENT_COMPAT;
601 } elseif ( $quote_style === 'single' ) {
602 $quote_style = ENT_NOQUOTES;
605 // Handle double encoding ourselves
606 if ( $double_encode ) {
607 $string = @htmlspecialchars( $string, $quote_style, $charset );
609 // Decode & into &
610 $string = wp_specialchars_decode( $string, $_quote_style );
612 // Guarantee every &entity; is valid or re-encode the &
613 $string = wp_kses_normalize_entities( $string );
615 // Now re-encode everything except &entity;
616 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
618 for ( $i = 0; $i < count( $string ); $i += 2 )
619 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
621 $string = implode( '', $string );
624 // Backwards compatibility
625 if ( 'single' === $_quote_style )
626 $string = str_replace( "'", ''', $string );
632 * Converts a number of HTML entities into their special characters.
634 * Specifically deals with: &, <, >, ", and '.
636 * $quote_style can be set to ENT_COMPAT to decode " entities,
637 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
641 * @param string $string The text which is to be decoded.
642 * @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.
643 * @return string The decoded text without HTML entities.
645 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
646 $string = (string) $string;
648 if ( 0 === strlen( $string ) ) {
652 // Don't bother if there are no entities - saves a lot of processing
653 if ( strpos( $string, '&' ) === false ) {
657 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
658 if ( empty( $quote_style ) ) {
659 $quote_style = ENT_NOQUOTES;
660 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
661 $quote_style = ENT_QUOTES;
664 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
665 $single = array( ''' => '\'', ''' => '\'' );
666 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
667 $double = array( '"' => '"', '"' => '"', '"' => '"' );
668 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
669 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
670 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
672 if ( $quote_style === ENT_QUOTES ) {
673 $translation = array_merge( $single, $double, $others );
674 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
675 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
676 $translation = array_merge( $double, $others );
677 $translation_preg = array_merge( $double_preg, $others_preg );
678 } elseif ( $quote_style === 'single' ) {
679 $translation = array_merge( $single, $others );
680 $translation_preg = array_merge( $single_preg, $others_preg );
681 } elseif ( $quote_style === ENT_NOQUOTES ) {
682 $translation = $others;
683 $translation_preg = $others_preg;
686 // Remove zero padding on numeric entities
687 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
689 // Replace characters according to translation table
690 return strtr( $string, $translation );
694 * Checks for invalid UTF8 in a string.
698 * @param string $string The text which is to be checked.
699 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
700 * @return string The checked text.
702 function wp_check_invalid_utf8( $string, $strip = false ) {
703 $string = (string) $string;
705 if ( 0 === strlen( $string ) ) {
709 // Store the site charset as a static to avoid multiple calls to get_option()
711 if ( !isset( $is_utf8 ) ) {
712 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
718 // Check for support for utf8 in the installed PCRE library once and store the result in a static
720 if ( !isset( $utf8_pcre ) ) {
721 $utf8_pcre = @preg_match( '/^./u', 'a' );
723 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
728 // preg_match fails when it encounters invalid UTF8 in $string
729 if ( 1 === @preg_match( '/^./us', $string ) ) {
733 // Attempt to strip the bad chars if requested (not recommended)
734 if ( $strip && function_exists( 'iconv' ) ) {
735 return iconv( 'utf-8', 'utf-8', $string );
742 * Encode the Unicode values to be used in the URI.
746 * @param string $utf8_string
747 * @param int $length Max length of the string
748 * @return string String with Unicode encoded for URI.
750 function utf8_uri_encode( $utf8_string, $length = 0 ) {
756 mbstring_binary_safe_encoding();
757 $string_length = strlen( $utf8_string );
758 reset_mbstring_encoding();
760 for ($i = 0; $i < $string_length; $i++ ) {
762 $value = ord( $utf8_string[ $i ] );
764 if ( $value < 128 ) {
765 if ( $length && ( $unicode_length >= $length ) )
767 $unicode .= chr($value);
770 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
774 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
776 if ( count( $values ) == $num_octets ) {
777 if ($num_octets == 3) {
778 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
779 $unicode_length += 9;
781 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
782 $unicode_length += 6;
795 * Converts all accent characters to ASCII characters.
797 * If there are no accent characters, then the string given is just returned.
801 * @param string $string Text that might have accent characters
802 * @return string Filtered string with replaced "nice" characters.
804 function remove_accents($string) {
805 if ( !preg_match('/[\x80-\xff]/', $string) )
808 if (seems_utf8($string)) {
810 // Decompositions for Latin-1 Supplement
811 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
812 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
813 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
814 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
815 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
816 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
817 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
818 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
819 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
820 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
821 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
822 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
823 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
824 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
825 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
826 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
827 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
828 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
829 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
830 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
831 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
832 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
833 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
834 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
835 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
836 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
837 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
838 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
839 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
840 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
841 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
842 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
843 // Decompositions for Latin Extended-A
844 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
845 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
846 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
847 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
848 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
849 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
850 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
851 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
852 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
853 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
854 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
855 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
856 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
857 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
858 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
859 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
860 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
861 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
862 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
863 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
864 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
865 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
866 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
867 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
868 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
869 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
870 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
871 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
872 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
873 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
874 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
875 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
876 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
877 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
878 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
879 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
880 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
881 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
882 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
883 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
884 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
885 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
886 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
887 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
888 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
889 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
890 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
891 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
892 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
893 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
894 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
895 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
896 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
897 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
898 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
899 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
900 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
901 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
902 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
903 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
904 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
905 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
906 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
907 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
908 // Decompositions for Latin Extended-B
909 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
910 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
912 chr(226).chr(130).chr(172) => 'E',
914 chr(194).chr(163) => '',
915 // Vowels with diacritic (Vietnamese)
917 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
918 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
920 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
921 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
922 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
923 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
924 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
925 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
926 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
928 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
929 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
930 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
931 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
932 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
933 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
934 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
935 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
936 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
937 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
938 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
939 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
941 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
942 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
943 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
944 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
945 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
946 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
947 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
948 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
950 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
951 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
952 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
953 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
954 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
955 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
957 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
958 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
959 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
960 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
961 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
962 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
963 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
964 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
965 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
966 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
967 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
968 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
969 // Vowels with diacritic (Chinese, Hanyu Pinyin)
970 chr(201).chr(145) => 'a',
972 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
974 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
976 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
977 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
978 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
979 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
980 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
982 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
985 // Used for locale-specific rules
986 $locale = get_locale();
988 if ( 'de_DE' == $locale ) {
989 $chars[ chr(195).chr(132) ] = 'Ae';
990 $chars[ chr(195).chr(164) ] = 'ae';
991 $chars[ chr(195).chr(150) ] = 'Oe';
992 $chars[ chr(195).chr(182) ] = 'oe';
993 $chars[ chr(195).chr(156) ] = 'Ue';
994 $chars[ chr(195).chr(188) ] = 'ue';
995 $chars[ chr(195).chr(159) ] = 'ss';
996 } elseif ( 'da_DK' === $locale ) {
997 $chars[ chr(195).chr(134) ] = 'Ae';
998 $chars[ chr(195).chr(166) ] = 'ae';
999 $chars[ chr(195).chr(152) ] = 'Oe';
1000 $chars[ chr(195).chr(184) ] = 'oe';
1001 $chars[ chr(195).chr(133) ] = 'Aa';
1002 $chars[ chr(195).chr(165) ] = 'aa';
1005 $string = strtr($string, $chars);
1007 // Assume ISO-8859-1 if not UTF-8
1008 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1009 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1010 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1011 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1012 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1013 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1014 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1015 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1016 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1017 .chr(252).chr(253).chr(255);
1019 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1021 $string = strtr($string, $chars['in'], $chars['out']);
1022 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1023 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1024 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1031 * Sanitizes a filename, replacing whitespace with dashes.
1033 * Removes special characters that are illegal in filenames on certain
1034 * operating systems and special characters requiring special escaping
1035 * to manipulate at the command line. Replaces spaces and consecutive
1036 * dashes with a single dash. Trims period, dash and underscore from beginning
1037 * and end of filename.
1041 * @param string $filename The filename to be sanitized
1042 * @return string The sanitized filename
1044 function sanitize_file_name( $filename ) {
1045 $filename_raw = $filename;
1046 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1048 * Filter the list of characters to remove from a filename.
1052 * @param array $special_chars Characters to remove.
1053 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1055 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1056 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1057 $filename = str_replace($special_chars, '', $filename);
1058 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1059 $filename = preg_replace('/[\s-]+/', '-', $filename);
1060 $filename = trim($filename, '.-_');
1062 // Split the filename into a base and extension[s]
1063 $parts = explode('.', $filename);
1065 // Return if only one extension
1066 if ( count( $parts ) <= 2 ) {
1068 * Filter a sanitized filename string.
1072 * @param string $filename Sanitized filename.
1073 * @param string $filename_raw The filename prior to sanitization.
1075 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1078 // Process multiple extensions
1079 $filename = array_shift($parts);
1080 $extension = array_pop($parts);
1081 $mimes = get_allowed_mime_types();
1084 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1085 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1087 foreach ( (array) $parts as $part) {
1088 $filename .= '.' . $part;
1090 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1092 foreach ( $mimes as $ext_preg => $mime_match ) {
1093 $ext_preg = '!^(' . $ext_preg . ')$!i';
1094 if ( preg_match( $ext_preg, $part ) ) {
1103 $filename .= '.' . $extension;
1104 /** This filter is documented in wp-includes/formatting.php */
1105 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1109 * Sanitizes a username, stripping out unsafe characters.
1111 * Removes tags, octets, entities, and if strict is enabled, will only keep
1112 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1113 * raw username (the username in the parameter), and the value of $strict as
1114 * parameters for the 'sanitize_user' filter.
1118 * @param string $username The username to be sanitized.
1119 * @param bool $strict If set limits $username to specific characters. Default false.
1120 * @return string The sanitized username, after passing through filters.
1122 function sanitize_user( $username, $strict = false ) {
1123 $raw_username = $username;
1124 $username = wp_strip_all_tags( $username );
1125 $username = remove_accents( $username );
1127 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1128 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1130 // If strict, reduce to ASCII for max portability.
1132 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1134 $username = trim( $username );
1135 // Consolidate contiguous whitespace
1136 $username = preg_replace( '|\s+|', ' ', $username );
1139 * Filter a sanitized username string.
1143 * @param string $username Sanitized username.
1144 * @param string $raw_username The username prior to sanitization.
1145 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1147 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1151 * Sanitizes a string key.
1153 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1157 * @param string $key String key
1158 * @return string Sanitized key
1160 function sanitize_key( $key ) {
1162 $key = strtolower( $key );
1163 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1166 * Filter a sanitized key string.
1170 * @param string $key Sanitized key.
1171 * @param string $raw_key The key prior to sanitization.
1173 return apply_filters( 'sanitize_key', $key, $raw_key );
1177 * Sanitizes a title, or returns a fallback title.
1179 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1180 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1185 * @param string $title The string to be sanitized.
1186 * @param string $fallback_title Optional. A title to use if $title is empty.
1187 * @param string $context Optional. The operation for which the string is sanitized
1188 * @return string The sanitized string.
1190 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1191 $raw_title = $title;
1193 if ( 'save' == $context )
1194 $title = remove_accents($title);
1197 * Filter a sanitized title string.
1201 * @param string $title Sanitized title.
1202 * @param string $raw_title The title prior to sanitization.
1203 * @param string $context The context for which the title is being sanitized.
1205 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1207 if ( '' === $title || false === $title )
1208 $title = $fallback_title;
1214 * Sanitizes a title with the 'query' context.
1216 * Used for querying the database for a value from URL.
1219 * @uses sanitize_title()
1221 * @param string $title The string to be sanitized.
1222 * @return string The sanitized string.
1224 function sanitize_title_for_query( $title ) {
1225 return sanitize_title( $title, '', 'query' );
1229 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1231 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1232 * Whitespace becomes a dash.
1236 * @param string $title The title to be sanitized.
1237 * @param string $raw_title Optional. Not used.
1238 * @param string $context Optional. The operation for which the string is sanitized.
1239 * @return string The sanitized title.
1241 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1242 $title = strip_tags($title);
1243 // Preserve escaped octets.
1244 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1245 // Remove percent signs that are not part of an octet.
1246 $title = str_replace('%', '', $title);
1248 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1250 if (seems_utf8($title)) {
1251 if (function_exists('mb_strtolower')) {
1252 $title = mb_strtolower($title, 'UTF-8');
1254 $title = utf8_uri_encode($title, 200);
1257 $title = strtolower($title);
1258 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1259 $title = str_replace('.', '-', $title);
1261 if ( 'save' == $context ) {
1262 // Convert nbsp, ndash and mdash to hyphens
1263 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1265 // Strip these characters entirely
1266 $title = str_replace( array(
1270 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1272 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1273 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1274 // copy, reg, deg, hellip and trade
1275 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1277 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1278 // grave accent, macron, caron
1279 '%cc%80', '%cc%84', '%cc%8c',
1282 // Convert times to x
1283 $title = str_replace( '%c3%97', 'x', $title );
1286 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1287 $title = preg_replace('/\s+/', '-', $title);
1288 $title = preg_replace('|-+|', '-', $title);
1289 $title = trim($title, '-');
1295 * Ensures a string is a valid SQL order by clause.
1297 * Accepts one or more columns, with or without ASC/DESC, and also accepts
1302 * @param string $orderby Order by string to be checked.
1303 * @return string|bool Returns the order by clause if it is a match, false otherwise.
1305 function sanitize_sql_orderby( $orderby ){
1306 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
1313 * Sanitizes an HTML classname to ensure it only contains valid characters.
1315 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1316 * string then it will return the alternative value supplied.
1318 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1322 * @param string $class The classname to be sanitized
1323 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1324 * Defaults to an empty string.
1325 * @return string The sanitized value
1327 function sanitize_html_class( $class, $fallback = '' ) {
1328 //Strip out any % encoded octets
1329 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1331 //Limit to A-Z,a-z,0-9,_,-
1332 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1334 if ( '' == $sanitized )
1335 $sanitized = $fallback;
1338 * Filter a sanitized HTML class string.
1342 * @param string $sanitized The sanitized HTML class.
1343 * @param string $class HTML class before sanitization.
1344 * @param string $fallback The fallback string.
1346 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1350 * Converts a number of characters from a string.
1352 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
1353 * converted into correct XHTML and Unicode characters are converted to the
1358 * @param string $content String of characters to be converted.
1359 * @param string $deprecated Not used.
1360 * @return string Converted string.
1362 function convert_chars($content, $deprecated = '') {
1363 if ( !empty( $deprecated ) )
1364 _deprecated_argument( __FUNCTION__, '0.71' );
1366 // Translation of invalid Unicode references range to valid range
1367 $wp_htmltranswinuni = array(
1368 '€' => '€', // the Euro sign
1370 '‚' => '‚', // these are Windows CP1252 specific characters
1371 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1372 '„' => '„',
1373 '…' => '…',
1374 '†' => '†',
1375 '‡' => '‡',
1376 'ˆ' => 'ˆ',
1377 '‰' => '‰',
1378 'Š' => 'Š',
1379 '‹' => '‹',
1380 'Œ' => 'Œ',
1382 'Ž' => 'Ž',
1385 '‘' => '‘',
1386 '’' => '’',
1387 '“' => '“',
1388 '”' => '”',
1389 '•' => '•',
1390 '–' => '–',
1391 '—' => '—',
1392 '˜' => '˜',
1393 '™' => '™',
1394 'š' => 'š',
1395 '›' => '›',
1396 'œ' => 'œ',
1398 'ž' => 'ž',
1399 'Ÿ' => 'Ÿ'
1402 // Remove metadata tags
1403 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1404 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1406 // Converts lone & characters into & (a.k.a. &)
1407 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1410 $content = strtr($content, $wp_htmltranswinuni);
1412 // Just a little XHTML help
1413 $content = str_replace('<br>', '<br />', $content);
1414 $content = str_replace('<hr>', '<hr />', $content);
1420 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1424 * @param string $text Text to be balanced
1425 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1426 * @return string Balanced text
1428 function balanceTags( $text, $force = false ) {
1429 if ( $force || get_option('use_balanceTags') == 1 ) {
1430 return force_balance_tags( $text );
1437 * Balances tags of string using a modified stack.
1441 * @author Leonard Lin <leonard@acm.org>
1443 * @copyright November 4, 2001
1445 * @todo Make better - change loop condition to $text in 1.2
1446 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1447 * 1.1 Fixed handling of append/stack pop order of end text
1448 * Added Cleaning Hooks
1451 * @param string $text Text to be balanced.
1452 * @return string Balanced text.
1454 function force_balance_tags( $text ) {
1455 $tagstack = array();
1459 // Known single-entity/self-closing tags
1460 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1461 // Tags that can be immediately nested within themselves
1462 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1464 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1465 $text = str_replace('< !--', '< !--', $text);
1466 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1467 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1469 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1470 $newtext .= $tagqueue;
1472 $i = strpos($text, $regex[0]);
1473 $l = strlen($regex[0]);
1475 // clear the shifter
1478 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1479 $tag = strtolower(substr($regex[1],1));
1480 // if too many closing tags
1481 if( $stacksize <= 0 ) {
1483 // or close to be safe $tag = '/' . $tag;
1485 // if stacktop value = tag close value then pop
1486 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1487 $tag = '</' . $tag . '>'; // Close Tag
1489 array_pop( $tagstack );
1491 } else { // closing tag not at top, search for it
1492 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1493 if ( $tagstack[$j] == $tag ) {
1494 // add tag to tagqueue
1495 for ( $k = $stacksize-1; $k >= $j; $k--) {
1496 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1504 } else { // Begin Tag
1505 $tag = strtolower($regex[1]);
1509 // If it's an empty tag "< >", do nothing
1513 // ElseIf it presents itself as a self-closing tag...
1514 elseif ( substr( $regex[2], -1 ) == '/' ) {
1515 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1516 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1517 if ( ! in_array( $tag, $single_tags ) )
1518 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1520 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1521 elseif ( in_array($tag, $single_tags) ) {
1524 // Else it's not a single-entity tag
1526 // If the top of the stack is the same as the tag we want to push, close previous tag
1527 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1528 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1531 $stacksize = array_push( $tagstack, $tag );
1535 $attributes = $regex[2];
1536 if( ! empty( $attributes ) && $attributes[0] != '>' )
1537 $attributes = ' ' . $attributes;
1539 $tag = '<' . $tag . $attributes . '>';
1540 //If already queuing a close tag, then put this tag on, too
1541 if ( !empty($tagqueue) ) {
1546 $newtext .= substr($text, 0, $i) . $tag;
1547 $text = substr($text, $i + $l);
1551 $newtext .= $tagqueue;
1553 // Add Remaining text
1557 while( $x = array_pop($tagstack) )
1558 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1560 // WP fix for the bug with HTML comments
1561 $newtext = str_replace("< !--","<!--",$newtext);
1562 $newtext = str_replace("< !--","< !--",$newtext);
1568 * Acts on text which is about to be edited.
1570 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1571 * to convert special characters to HTML entities. If $richedit is set to true,
1572 * it is simply a holder for the 'format_to_edit' filter.
1576 * @param string $content The text about to be edited.
1577 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1578 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1580 function format_to_edit( $content, $richedit = false ) {
1582 * Filter the text to be formatted for editing.
1586 * @param string $content The text, prior to formatting for editing.
1588 $content = apply_filters( 'format_to_edit', $content );
1590 $content = esc_textarea( $content );
1595 * Add leading zeros when necessary.
1597 * If you set the threshold to '4' and the number is '10', then you will get
1598 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1599 * will get back '5000'.
1601 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1602 * and the size of the number. If the number is large enough, then no zeros will
1607 * @param mixed $number Number to append zeros to if not greater than threshold.
1608 * @param int $threshold Digit places number needs to be to not have zeros added.
1609 * @return string Adds leading zeros to number if needed.
1611 function zeroise($number, $threshold) {
1612 return sprintf('%0'.$threshold.'s', $number);
1616 * Adds backslashes before letters and before a number at the start of a string.
1620 * @param string $string Value to which backslashes will be added.
1621 * @return string String with backslashes inserted.
1623 function backslashit($string) {
1624 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1625 $string = '\\\\' . $string;
1626 return addcslashes( $string, 'A..Za..z' );
1630 * Appends a trailing slash.
1632 * Will remove trailing forward and backslashes if it exists already before adding
1633 * a trailing forward slash. This prevents double slashing a string or path.
1635 * The primary use of this is for paths and thus should be used for paths. It is
1636 * not restricted to paths and offers no specific path support.
1640 * @param string $string What to add the trailing slash to.
1641 * @return string String with trailing slash added.
1643 function trailingslashit( $string ) {
1644 return untrailingslashit( $string ) . '/';
1648 * Removes trailing forward slashes and backslashes if they exist.
1650 * The primary use of this is for paths and thus should be used for paths. It is
1651 * not restricted to paths and offers no specific path support.
1655 * @param string $string What to remove the trailing slashes from.
1656 * @return string String without the trailing slashes.
1658 function untrailingslashit( $string ) {
1659 return rtrim( $string, '/\\' );
1663 * Adds slashes to escape strings.
1665 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1666 * http://www.php.net/magic_quotes} for more details.
1670 * @param string $gpc The string returned from HTTP request data.
1671 * @return string Returns a string escaped with slashes.
1673 function addslashes_gpc($gpc) {
1674 if ( get_magic_quotes_gpc() )
1675 $gpc = stripslashes($gpc);
1677 return wp_slash($gpc);
1681 * Navigates through an array and removes slashes from the values.
1683 * If an array is passed, the array_map() function causes a callback to pass the
1684 * value back to the function. The slashes from this value will removed.
1688 * @param mixed $value The value to be stripped.
1689 * @return mixed Stripped value.
1691 function stripslashes_deep($value) {
1692 if ( is_array($value) ) {
1693 $value = array_map('stripslashes_deep', $value);
1694 } elseif ( is_object($value) ) {
1695 $vars = get_object_vars( $value );
1696 foreach ($vars as $key=>$data) {
1697 $value->{$key} = stripslashes_deep( $data );
1699 } elseif ( is_string( $value ) ) {
1700 $value = stripslashes($value);
1707 * Navigates through an array and encodes the values to be used in a URL.
1712 * @param array|string $value The array or string to be encoded.
1713 * @return array|string $value The encoded array (or string from the callback).
1715 function urlencode_deep($value) {
1716 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1721 * Navigates through an array and raw encodes the values to be used in a URL.
1725 * @param array|string $value The array or string to be encoded.
1726 * @return array|string $value The encoded array (or string from the callback).
1728 function rawurlencode_deep( $value ) {
1729 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1733 * Converts email addresses characters to HTML entities to block spam bots.
1737 * @param string $email_address Email address.
1738 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
1739 * @return string Converted email address.
1741 function antispambot( $email_address, $hex_encoding = 0 ) {
1742 $email_no_spam_address = '';
1743 for ( $i = 0; $i < strlen( $email_address ); $i++ ) {
1744 $j = rand( 0, 1 + $hex_encoding );
1746 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
1747 } elseif ( $j == 1 ) {
1748 $email_no_spam_address .= $email_address[$i];
1749 } elseif ( $j == 2 ) {
1750 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
1754 $email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
1756 return $email_no_spam_address;
1760 * Callback to convert URI match to HTML A element.
1762 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1763 * make_clickable()}.
1768 * @param array $matches Single Regex Match.
1769 * @return string HTML A element with URI address.
1771 function _make_url_clickable_cb($matches) {
1774 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1775 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1776 // Then we can let the parenthesis balancer do its thing below.
1777 $url .= $matches[3];
1780 $suffix = $matches[3];
1783 // Include parentheses in the URL only if paired
1784 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1785 $suffix = strrchr( $url, ')' ) . $suffix;
1786 $url = substr( $url, 0, strrpos( $url, ')' ) );
1789 $url = esc_url($url);
1793 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1797 * Callback to convert URL match to HTML A element.
1799 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1800 * make_clickable()}.
1805 * @param array $matches Single Regex Match.
1806 * @return string HTML A element with URL address.
1808 function _make_web_ftp_clickable_cb($matches) {
1810 $dest = $matches[2];
1811 $dest = 'http://' . $dest;
1812 $dest = esc_url($dest);
1816 // removed trailing [.,;:)] from URL
1817 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1818 $ret = substr($dest, -1);
1819 $dest = substr($dest, 0, strlen($dest)-1);
1821 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1825 * Callback to convert email address match to HTML A element.
1827 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1828 * make_clickable()}.
1833 * @param array $matches Single Regex Match.
1834 * @return string HTML A element with email address.
1836 function _make_email_clickable_cb($matches) {
1837 $email = $matches[2] . '@' . $matches[3];
1838 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1842 * Convert plaintext URI to HTML links.
1844 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1849 * @param string $text Content to convert URIs.
1850 * @return string Content with converted URIs.
1852 function make_clickable( $text ) {
1854 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
1855 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
1856 foreach ( $textarr as $piece ) {
1858 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
1860 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
1863 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
1868 // Long strings might contain expensive edge cases ...
1869 if ( 10000 < strlen( $piece ) ) {
1871 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
1872 if ( 2101 < strlen( $chunk ) ) {
1873 $r .= $chunk; // Too big, no whitespace: bail.
1875 $r .= make_clickable( $chunk );
1879 $ret = " $piece "; // Pad with whitespace to simplify the regexes
1882 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
1884 [\\w]{1,20}+:// # Scheme and hier-part prefix
1885 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
1886 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
1887 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
1888 [\'.,;:!?)] # Punctuation URL character
1889 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
1892 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
1893 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
1894 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
1896 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
1898 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
1899 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
1901 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
1906 // Cleanup of accidental links within links
1907 $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
1912 * Breaks a string into chunks by splitting at whitespace characters.
1913 * The length of each returned chunk is as close to the specified length goal as possible,
1914 * with the caveat that each chunk includes its trailing delimiter.
1915 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
1917 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
1919 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
1922 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
1924 * 0 => '1234 67890 ', // 11 characters: Perfect split
1925 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
1926 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
1927 * 3 => '1234 890 ', // 11 characters: Perfect split
1928 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
1929 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
1930 * 6 => ' 45678 ', // 11 characters: Perfect split
1931 * 7 => '1 3 5 7 9', // 9 characters: End of $string
1938 * @param string $string The string to split.
1939 * @param int $goal The desired chunk length.
1940 * @return array Numeric array of chunks.
1942 function _split_str_by_whitespace( $string, $goal ) {
1945 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
1947 while ( $goal < strlen( $string_nullspace ) ) {
1948 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
1950 if ( false === $pos ) {
1951 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
1952 if ( false === $pos ) {
1957 $chunks[] = substr( $string, 0, $pos + 1 );
1958 $string = substr( $string, $pos + 1 );
1959 $string_nullspace = substr( $string_nullspace, $pos + 1 );
1963 $chunks[] = $string;
1970 * Adds rel nofollow string to all HTML A elements in content.
1974 * @param string $text Content that may contain HTML A elements.
1975 * @return string Converted content.
1977 function wp_rel_nofollow( $text ) {
1978 // This is a pre save filter, so text is already escaped.
1979 $text = stripslashes($text);
1980 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1981 $text = wp_slash($text);
1986 * Callback to add rel=nofollow string to HTML A element.
1988 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1989 * string to prevent from invalidating (X)HTML.
1993 * @param array $matches Single Match
1994 * @return string HTML A Element with rel nofollow.
1996 function wp_rel_nofollow_callback( $matches ) {
1997 $text = $matches[1];
1998 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1999 return "<a $text rel=\"nofollow\">";
2003 * Convert one smiley code to the icon graphic file equivalent.
2005 * Callback handler for {@link convert_smilies()}.
2006 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2007 * <img> string for that smiley.
2009 * @global array $wpsmiliestrans
2012 * @param array $matches Single match. Smiley code to convert to image.
2013 * @return string Image string for smiley.
2015 function translate_smiley( $matches ) {
2016 global $wpsmiliestrans;
2018 if ( count( $matches ) == 0 )
2021 $smiley = trim( reset( $matches ) );
2022 $img = $wpsmiliestrans[ $smiley ];
2025 * Filter the Smiley image URL before it's used in the image element.
2029 * @param string $smiley_url URL for the smiley image.
2030 * @param string $img Filename for the smiley image.
2031 * @param string $site_url Site URL, as returned by site_url().
2033 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2035 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" />', esc_url( $src_url ), esc_attr( $smiley ) );
2039 * Convert text equivalent of smilies to images.
2041 * Will only convert smilies if the option 'use_smilies' is true and the global
2042 * used in the function isn't empty.
2045 * @uses $wp_smiliessearch
2047 * @param string $text Content to convert smilies from text.
2048 * @return string Converted content with text smilies replaced with images.
2050 function convert_smilies( $text ) {
2051 global $wp_smiliessearch;
2053 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2054 // HTML loop taken from texturize function, could possible be consolidated
2055 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2056 $stop = count( $textarr );// loop stuff
2058 // Ignore proessing of specific tags
2059 $tags_to_ignore = 'code|pre|style|script|textarea';
2060 $ignore_block_element = '';
2062 for ( $i = 0; $i < $stop; $i++ ) {
2063 $content = $textarr[$i];
2065 // If we're in an ignore block, wait until we find its closing tag
2066 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2067 $ignore_block_element = $matches[1];
2070 // If it's not a tag and not in ignore block
2071 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2072 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2075 // did we exit ignore block
2076 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2077 $ignore_block_element = '';
2080 $output .= $content;
2083 // return default text.
2090 * Verifies that an email is valid.
2092 * Does not grok i18n domains. Not RFC compliant.
2096 * @param string $email Email address to verify.
2097 * @param boolean $deprecated Deprecated.
2098 * @return string|bool Either false or the valid email address.
2100 function is_email( $email, $deprecated = false ) {
2101 if ( ! empty( $deprecated ) )
2102 _deprecated_argument( __FUNCTION__, '3.0' );
2104 // Test for the minimum length the email can be
2105 if ( strlen( $email ) < 3 ) {
2107 * Filter whether an email address is valid.
2109 * This filter is evaluated under several different contexts, such as 'email_too_short',
2110 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2111 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2115 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2116 * @param string $email The email address being checked.
2117 * @param string $message An explanatory message to the user.
2118 * @param string $context Context under which the email was tested.
2120 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2123 // Test for an @ character after the first position
2124 if ( strpos( $email, '@', 1 ) === false ) {
2125 /** This filter is documented in wp-includes/formatting.php */
2126 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2129 // Split out the local and domain parts
2130 list( $local, $domain ) = explode( '@', $email, 2 );
2133 // Test for invalid characters
2134 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2135 /** This filter is documented in wp-includes/formatting.php */
2136 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2140 // Test for sequences of periods
2141 if ( preg_match( '/\.{2,}/', $domain ) ) {
2142 /** This filter is documented in wp-includes/formatting.php */
2143 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2146 // Test for leading and trailing periods and whitespace
2147 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2148 /** This filter is documented in wp-includes/formatting.php */
2149 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2152 // Split the domain into subs
2153 $subs = explode( '.', $domain );
2155 // Assume the domain will have at least two subs
2156 if ( 2 > count( $subs ) ) {
2157 /** This filter is documented in wp-includes/formatting.php */
2158 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2161 // Loop through each sub
2162 foreach ( $subs as $sub ) {
2163 // Test for leading and trailing hyphens and whitespace
2164 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2165 /** This filter is documented in wp-includes/formatting.php */
2166 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2169 // Test for invalid characters
2170 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2171 /** This filter is documented in wp-includes/formatting.php */
2172 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2176 // Congratulations your email made it!
2177 /** This filter is documented in wp-includes/formatting.php */
2178 return apply_filters( 'is_email', $email, $email, null );
2182 * Convert to ASCII from email subjects.
2186 * @param string $string Subject line
2187 * @return string Converted string to ASCII
2189 function wp_iso_descrambler($string) {
2190 /* this may only work with iso-8859-1, I'm afraid */
2191 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2194 $subject = str_replace('_', ' ', $matches[2]);
2195 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
2201 * Helper function to convert hex encoded chars to ASCII
2206 * @param array $match The preg_replace_callback matches array
2207 * @return array Converted chars
2209 function _wp_iso_convert( $match ) {
2210 return chr( hexdec( strtolower( $match[1] ) ) );
2214 * Returns a date in the GMT equivalent.
2216 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2217 * timezone_string available, the date is assumed to be in that timezone,
2218 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2219 * format can be overridden using the $format parameter.
2223 * @uses get_option() to retrieve the value of 'gmt_offset'.
2224 * @param string $string The date to be converted.
2225 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2226 * @return string GMT version of the date provided.
2228 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2229 $tz = get_option( 'timezone_string' );
2231 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2233 return gmdate( $format, 0 );
2234 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2235 $string_gmt = $datetime->format( $format );
2237 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 ) )
2238 return gmdate( $format, 0 );
2239 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2240 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2246 * Converts a GMT date into the correct format for the blog.
2248 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2249 * timezone_string available, the returned date is in that timezone, otherwise
2250 * it simply adds the value of gmt_offset. Return format can be overridden
2251 * using the $format parameter
2255 * @param string $string The date to be converted.
2256 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2257 * @return string Formatted date relative to the timezone / GMT offset.
2259 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2260 $tz = get_option( 'timezone_string' );
2262 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2264 return date( $format, 0 );
2265 $datetime->setTimezone( new DateTimeZone( $tz ) );
2266 $string_localtime = $datetime->format( $format );
2268 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) )
2269 return date( $format, 0 );
2270 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2271 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2273 return $string_localtime;
2277 * Computes an offset in seconds from an iso8601 timezone.
2281 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2282 * @return int|float The offset in seconds.
2284 function iso8601_timezone_to_offset($timezone) {
2285 // $timezone is either 'Z' or '[+|-]hhmm'
2286 if ($timezone == 'Z') {
2289 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2290 $hours = intval(substr($timezone, 1, 2));
2291 $minutes = intval(substr($timezone, 3, 4)) / 60;
2292 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2298 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2302 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2303 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2304 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2306 function iso8601_to_datetime($date_string, $timezone = 'user') {
2307 $timezone = strtolower($timezone);
2309 if ($timezone == 'gmt') {
2311 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);
2313 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2314 $offset = iso8601_timezone_to_offset($date_bits[7]);
2315 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2316 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2319 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2320 $timestamp -= $offset;
2322 return gmdate('Y-m-d H:i:s', $timestamp);
2324 } else if ($timezone == 'user') {
2325 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);
2330 * Adds a element attributes to open links in new windows.
2332 * Comment text in popup windows should be filtered through this. Right now it's
2333 * a moderately dumb function, ideally it would detect whether a target or rel
2334 * attribute was already there and adjust its actions accordingly.
2338 * @param string $text Content to replace links to open in a new window.
2339 * @return string Content that has filtered links.
2341 function popuplinks($text) {
2342 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2347 * Strips out all characters that are not allowable in an email.
2351 * @param string $email Email address to filter.
2352 * @return string Filtered email address.
2354 function sanitize_email( $email ) {
2355 // Test for the minimum length the email can be
2356 if ( strlen( $email ) < 3 ) {
2358 * Filter a sanitized email address.
2360 * This filter is evaluated under several contexts, including 'email_too_short',
2361 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2362 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2366 * @param string $email The sanitized email address.
2367 * @param string $email The email address, as provided to sanitize_email().
2368 * @param string $message A message to pass to the user.
2370 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2373 // Test for an @ character after the first position
2374 if ( strpos( $email, '@', 1 ) === false ) {
2375 /** This filter is documented in wp-includes/formatting.php */
2376 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2379 // Split out the local and domain parts
2380 list( $local, $domain ) = explode( '@', $email, 2 );
2383 // Test for invalid characters
2384 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2385 if ( '' === $local ) {
2386 /** This filter is documented in wp-includes/formatting.php */
2387 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2391 // Test for sequences of periods
2392 $domain = preg_replace( '/\.{2,}/', '', $domain );
2393 if ( '' === $domain ) {
2394 /** This filter is documented in wp-includes/formatting.php */
2395 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2398 // Test for leading and trailing periods and whitespace
2399 $domain = trim( $domain, " \t\n\r\0\x0B." );
2400 if ( '' === $domain ) {
2401 /** This filter is documented in wp-includes/formatting.php */
2402 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2405 // Split the domain into subs
2406 $subs = explode( '.', $domain );
2408 // Assume the domain will have at least two subs
2409 if ( 2 > count( $subs ) ) {
2410 /** This filter is documented in wp-includes/formatting.php */
2411 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2414 // Create an array that will contain valid subs
2415 $new_subs = array();
2417 // Loop through each sub
2418 foreach ( $subs as $sub ) {
2419 // Test for leading and trailing hyphens
2420 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2422 // Test for invalid characters
2423 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2425 // If there's anything left, add it to the valid subs
2426 if ( '' !== $sub ) {
2431 // If there aren't 2 or more valid subs
2432 if ( 2 > count( $new_subs ) ) {
2433 /** This filter is documented in wp-includes/formatting.php */
2434 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2437 // Join valid subs into the new domain
2438 $domain = join( '.', $new_subs );
2440 // Put the email back together
2441 $email = $local . '@' . $domain;
2443 // Congratulations your email made it!
2444 /** This filter is documented in wp-includes/formatting.php */
2445 return apply_filters( 'sanitize_email', $email, $email, null );
2449 * Determines the difference between two timestamps.
2451 * The difference is returned in a human readable format such as "1 hour",
2452 * "5 mins", "2 days".
2456 * @param int $from Unix timestamp from which the difference begins.
2457 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2458 * @return string Human readable time difference.
2460 function human_time_diff( $from, $to = '' ) {
2461 if ( empty( $to ) ) {
2465 $diff = (int) abs( $to - $from );
2467 if ( $diff < HOUR_IN_SECONDS ) {
2468 $mins = round( $diff / MINUTE_IN_SECONDS );
2471 /* translators: min=minute */
2472 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2473 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2474 $hours = round( $diff / HOUR_IN_SECONDS );
2477 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2478 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2479 $days = round( $diff / DAY_IN_SECONDS );
2482 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2483 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2484 $weeks = round( $diff / WEEK_IN_SECONDS );
2487 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2488 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2489 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2492 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2493 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2494 $years = round( $diff / YEAR_IN_SECONDS );
2497 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2501 * Filter the human readable difference between two timestamps.
2505 * @param string $since The difference in human readable text.
2506 * @param int $diff The difference in seconds.
2507 * @param int $from Unix timestamp from which the difference begins.
2508 * @param int $to Unix timestamp to end the time difference.
2510 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2514 * Generates an excerpt from the content, if needed.
2516 * The excerpt word amount will be 55 words and if the amount is greater than
2517 * that, then the string ' […]' will be appended to the excerpt. If the string
2518 * is less than 55 words, then the content will be returned as is.
2520 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2521 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2525 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2526 * @return string The excerpt.
2528 function wp_trim_excerpt($text = '') {
2529 $raw_excerpt = $text;
2530 if ( '' == $text ) {
2531 $text = get_the_content('');
2533 $text = strip_shortcodes( $text );
2535 /** This filter is documented in wp-includes/post-template.php */
2536 $text = apply_filters( 'the_content', $text );
2537 $text = str_replace(']]>', ']]>', $text);
2540 * Filter the number of words in an excerpt.
2544 * @param int $number The number of words. Default 55.
2546 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2548 * Filter the string in the "more" link displayed after a trimmed excerpt.
2552 * @param string $more_string The string shown within the more link.
2554 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2555 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2558 * Filter the trimmed excerpt string.
2562 * @param string $text The trimmed text.
2563 * @param string $raw_excerpt The text prior to trimming.
2565 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2569 * Trims text to a certain number of words.
2571 * This function is localized. For languages that count 'words' by the individual
2572 * character (such as East Asian languages), the $num_words argument will apply
2573 * to the number of individual characters.
2577 * @param string $text Text to trim.
2578 * @param int $num_words Number of words. Default 55.
2579 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2580 * @return string Trimmed text.
2582 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2583 if ( null === $more )
2584 $more = __( '…' );
2585 $original_text = $text;
2586 $text = wp_strip_all_tags( $text );
2587 /* translators: If your word count is based on single characters (East Asian characters),
2588 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2589 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2590 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2591 preg_match_all( '/./u', $text, $words_array );
2592 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2595 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2598 if ( count( $words_array ) > $num_words ) {
2599 array_pop( $words_array );
2600 $text = implode( $sep, $words_array );
2601 $text = $text . $more;
2603 $text = implode( $sep, $words_array );
2606 * Filter the text content after words have been trimmed.
2610 * @param string $text The trimmed text.
2611 * @param int $num_words The number of words to trim the text to. Default 5.
2612 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2613 * @param string $original_text The text before it was trimmed.
2615 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2619 * Converts named entities into numbered entities.
2623 * @param string $text The text within which entities will be converted.
2624 * @return string Text with converted entities.
2626 function ent2ncr($text) {
2629 * Filter text before named entities are converted into numbered entities.
2631 * A non-null string must be returned for the filter to be evaluated.
2635 * @param null $converted_text The text to be converted. Default null.
2636 * @param string $text The text prior to entity conversion.
2638 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2639 if( null !== $filtered )
2643 '"' => '"',
2648 ' ' => ' ',
2649 '¡' => '¡',
2650 '¢' => '¢',
2651 '£' => '£',
2652 '¤' => '¤',
2653 '¥' => '¥',
2654 '¦' => '¦',
2655 '&brkbar;' => '¦',
2656 '§' => '§',
2657 '¨' => '¨',
2658 '¨' => '¨',
2659 '©' => '©',
2660 'ª' => 'ª',
2661 '«' => '«',
2662 '¬' => '¬',
2663 '­' => '­',
2664 '®' => '®',
2665 '¯' => '¯',
2666 '&hibar;' => '¯',
2667 '°' => '°',
2668 '±' => '±',
2669 '²' => '²',
2670 '³' => '³',
2671 '´' => '´',
2672 'µ' => 'µ',
2673 '¶' => '¶',
2674 '·' => '·',
2675 '¸' => '¸',
2676 '¹' => '¹',
2677 'º' => 'º',
2678 '»' => '»',
2679 '¼' => '¼',
2680 '½' => '½',
2681 '¾' => '¾',
2682 '¿' => '¿',
2683 'À' => 'À',
2684 'Á' => 'Á',
2685 'Â' => 'Â',
2686 'Ã' => 'Ã',
2687 'Ä' => 'Ä',
2688 'Å' => 'Å',
2689 'Æ' => 'Æ',
2690 'Ç' => 'Ç',
2691 'È' => 'È',
2692 'É' => 'É',
2693 'Ê' => 'Ê',
2694 'Ë' => 'Ë',
2695 'Ì' => 'Ì',
2696 'Í' => 'Í',
2697 'Î' => 'Î',
2698 'Ï' => 'Ï',
2699 'Ð' => 'Ð',
2700 'Ñ' => 'Ñ',
2701 'Ò' => 'Ò',
2702 'Ó' => 'Ó',
2703 'Ô' => 'Ô',
2704 'Õ' => 'Õ',
2705 'Ö' => 'Ö',
2706 '×' => '×',
2707 'Ø' => 'Ø',
2708 'Ù' => 'Ù',
2709 'Ú' => 'Ú',
2710 'Û' => 'Û',
2711 'Ü' => 'Ü',
2712 'Ý' => 'Ý',
2713 'Þ' => 'Þ',
2714 'ß' => 'ß',
2715 'à' => 'à',
2716 'á' => 'á',
2717 'â' => 'â',
2718 'ã' => 'ã',
2719 'ä' => 'ä',
2720 'å' => 'å',
2721 'æ' => 'æ',
2722 'ç' => 'ç',
2723 'è' => 'è',
2724 'é' => 'é',
2725 'ê' => 'ê',
2726 'ë' => 'ë',
2727 'ì' => 'ì',
2728 'í' => 'í',
2729 'î' => 'î',
2730 'ï' => 'ï',
2731 'ð' => 'ð',
2732 'ñ' => 'ñ',
2733 'ò' => 'ò',
2734 'ó' => 'ó',
2735 'ô' => 'ô',
2736 'õ' => 'õ',
2737 'ö' => 'ö',
2738 '÷' => '÷',
2739 'ø' => 'ø',
2740 'ù' => 'ù',
2741 'ú' => 'ú',
2742 'û' => 'û',
2743 'ü' => 'ü',
2744 'ý' => 'ý',
2745 'þ' => 'þ',
2746 'ÿ' => 'ÿ',
2747 'Œ' => 'Œ',
2748 'œ' => 'œ',
2749 'Š' => 'Š',
2750 'š' => 'š',
2751 'Ÿ' => 'Ÿ',
2752 'ƒ' => 'ƒ',
2753 'ˆ' => 'ˆ',
2754 '˜' => '˜',
2755 'Α' => 'Α',
2756 'Β' => 'Β',
2757 'Γ' => 'Γ',
2758 'Δ' => 'Δ',
2759 'Ε' => 'Ε',
2760 'Ζ' => 'Ζ',
2761 'Η' => 'Η',
2762 'Θ' => 'Θ',
2763 'Ι' => 'Ι',
2764 'Κ' => 'Κ',
2765 'Λ' => 'Λ',
2769 'Ο' => 'Ο',
2771 'Ρ' => 'Ρ',
2772 'Σ' => 'Σ',
2773 'Τ' => 'Τ',
2774 'Υ' => 'Υ',
2775 'Φ' => 'Φ',
2776 'Χ' => 'Χ',
2777 'Ψ' => 'Ψ',
2778 'Ω' => 'Ω',
2779 'α' => 'α',
2780 'β' => 'β',
2781 'γ' => 'γ',
2782 'δ' => 'δ',
2783 'ε' => 'ε',
2784 'ζ' => 'ζ',
2785 'η' => 'η',
2786 'θ' => 'θ',
2787 'ι' => 'ι',
2788 'κ' => 'κ',
2789 'λ' => 'λ',
2793 'ο' => 'ο',
2795 'ρ' => 'ρ',
2796 'ς' => 'ς',
2797 'σ' => 'σ',
2798 'τ' => 'τ',
2799 'υ' => 'υ',
2800 'φ' => 'φ',
2801 'χ' => 'χ',
2802 'ψ' => 'ψ',
2803 'ω' => 'ω',
2804 'ϑ' => 'ϑ',
2805 'ϒ' => 'ϒ',
2806 'ϖ' => 'ϖ',
2807 ' ' => ' ',
2808 ' ' => ' ',
2809 ' ' => ' ',
2810 '‌' => '‌',
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 '♦' => '♦'
2901 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2905 * Formats text for the rich text editor.
2907 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2908 * be applied to an empty string.
2912 * @param string $text The text to be formatted.
2913 * @return string The formatted text after filter is applied.
2915 function wp_richedit_pre($text) {
2916 if ( empty( $text ) ) {
2918 * Filter text returned for the rich text editor.
2920 * This filter is first evaluated, and the value returned, if an empty string
2921 * is passed to wp_richedit_pre(). If an empty string is passed, it results
2922 * in a break tag and line feed.
2924 * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
2925 * return after being formatted.
2929 * @param string $output Text for the rich text editor.
2931 return apply_filters( 'richedit_pre', '' );
2934 $output = convert_chars($text);
2935 $output = wpautop($output);
2936 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
2938 /** This filter is documented in wp-includes/formatting.php */
2939 return apply_filters( 'richedit_pre', $output );
2943 * Formats text for the HTML editor.
2945 * Unless $output is empty it will pass through htmlspecialchars before the
2946 * 'htmledit_pre' filter is applied.
2950 * @param string $output The text to be formatted.
2951 * @return string Formatted text after filter applied.
2953 function wp_htmledit_pre($output) {
2954 if ( !empty($output) )
2955 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
2958 * Filter the text before it is formatted for the HTML editor.
2962 * @param string $output The HTML-formatted text.
2964 return apply_filters( 'htmledit_pre', $output );
2968 * Perform a deep string replace operation to ensure the values in $search are no longer present
2970 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2971 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2972 * str_replace would return
2977 * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
2978 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
2979 * @return string The string with the replaced svalues.
2981 function _deep_replace( $search, $subject ) {
2982 $subject = (string) $subject;
2986 $subject = str_replace( $search, '', $subject, $count );
2993 * Escapes data for use in a MySQL query.
2995 * Usually you should prepare queries using wpdb::prepare().
2996 * Sometimes, spot-escaping is required or useful. One example
2997 * is preparing an array for use in an IN clause.
3000 * @param string|array $data Unescaped data
3001 * @return string|array Escaped data
3003 function esc_sql( $data ) {
3005 return $wpdb->_escape( $data );
3009 * Checks and cleans a URL.
3011 * A number of characters are removed from the URL. If the URL is for displaying
3012 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3013 * is applied to the returned cleaned URL.
3016 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
3017 * via $protocols or the common ones set in the function.
3019 * @param string $url The URL to be cleaned.
3020 * @param array $protocols Optional. An array of acceptable protocols.
3021 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
3022 * @param string $_context Private. Use esc_url_raw() for database usage.
3023 * @return string The cleaned $url after the 'clean_url' filter is applied.
3025 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3026 $original_url = $url;
3030 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3031 $strip = array('%0d', '%0a', '%0D', '%0A');
3032 $url = _deep_replace($strip, $url);
3033 $url = str_replace(';//', '://', $url);
3034 /* If the URL doesn't appear to contain a scheme, we
3035 * presume it needs http:// appended (unless a relative
3036 * link starting with /, # or ? or a php file).
3038 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3039 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3040 $url = 'http://' . $url;
3042 // Replace ampersands and single quotes only when displaying.
3043 if ( 'display' == $_context ) {
3044 $url = wp_kses_normalize_entities( $url );
3045 $url = str_replace( '&', '&', $url );
3046 $url = str_replace( "'", ''', $url );
3049 if ( '/' === $url[0] ) {
3050 $good_protocol_url = $url;
3052 if ( ! is_array( $protocols ) )
3053 $protocols = wp_allowed_protocols();
3054 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3055 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3060 * Filter a string cleaned and escaped for output as a URL.
3064 * @param string $good_protocol_url The cleaned URL to be returned.
3065 * @param string $original_url The URL prior to cleaning.
3066 * @param string $_context If 'display', replace ampersands and single quotes only.
3068 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3072 * Performs esc_url() for database usage.
3077 * @param string $url The URL to be cleaned.
3078 * @param array $protocols An array of acceptable protocols.
3079 * @return string The cleaned URL.
3081 function esc_url_raw( $url, $protocols = null ) {
3082 return esc_url( $url, $protocols, 'db' );
3086 * Convert entities, while preserving already-encoded entities.
3088 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3092 * @param string $myHTML The text to be converted.
3093 * @return string Converted text.
3095 function htmlentities2($myHTML) {
3096 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3097 $translation_table[chr(38)] = '&';
3098 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3102 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3104 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3105 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3106 * be in single quotes. The filter 'js_escape' is also applied here.
3110 * @param string $text The text to be escaped.
3111 * @return string Escaped text.
3113 function esc_js( $text ) {
3114 $safe_text = wp_check_invalid_utf8( $text );
3115 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3116 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3117 $safe_text = str_replace( "\r", '', $safe_text );
3118 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3120 * Filter a string cleaned and escaped for output in JavaScript.
3122 * Text passed to esc_js() is stripped of invalid or special characters,
3123 * and properly slashed for output.
3127 * @param string $safe_text The text after it has been escaped.
3128 * @param string $text The text prior to being escaped.
3130 return apply_filters( 'js_escape', $safe_text, $text );
3134 * Escaping for HTML blocks.
3138 * @param string $text
3141 function esc_html( $text ) {
3142 $safe_text = wp_check_invalid_utf8( $text );
3143 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3145 * Filter a string cleaned and escaped for output in HTML.
3147 * Text passed to esc_html() is stripped of invalid or special characters
3152 * @param string $safe_text The text after it has been escaped.
3153 * @param string $text The text prior to being escaped.
3155 return apply_filters( 'esc_html', $safe_text, $text );
3159 * Escaping for HTML attributes.
3163 * @param string $text
3166 function esc_attr( $text ) {
3167 $safe_text = wp_check_invalid_utf8( $text );
3168 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3170 * Filter a string cleaned and escaped for output in an HTML attribute.
3172 * Text passed to esc_attr() is stripped of invalid or special characters
3177 * @param string $safe_text The text after it has been escaped.
3178 * @param string $text The text prior to being escaped.
3180 return apply_filters( 'attribute_escape', $safe_text, $text );
3184 * Escaping for textarea values.
3188 * @param string $text
3191 function esc_textarea( $text ) {
3192 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3194 * Filter a string cleaned and escaped for output in a textarea element.
3198 * @param string $safe_text The text after it has been escaped.
3199 * @param string $text The text prior to being escaped.
3201 return apply_filters( 'esc_textarea', $safe_text, $text );
3205 * Escape an HTML tag name.
3209 * @param string $tag_name
3212 function tag_escape($tag_name) {
3213 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3215 * Filter a string cleaned and escaped for output as an HTML tag.
3219 * @param string $safe_tag The tag name after it has been escaped.
3220 * @param string $tag_name The text before it was escaped.
3222 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3226 * Convert full URL paths to absolute paths.
3228 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3229 * beginning, so it isn't a true relative link, but from the web root base.
3233 * @param string $link Full URL path.
3234 * @return string Absolute path.
3236 function wp_make_link_relative( $link ) {
3237 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
3241 * Sanitises various option values based on the nature of the option.
3243 * This is basically a switch statement which will pass $value through a number
3244 * of functions depending on the $option.
3248 * @param string $option The name of the option.
3249 * @param string $value The unsanitised value.
3250 * @return string Sanitized value.
3252 function sanitize_option($option, $value) {
3254 switch ( $option ) {
3255 case 'admin_email' :
3256 case 'new_admin_email' :
3257 $value = sanitize_email( $value );
3258 if ( ! is_email( $value ) ) {
3259 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3260 if ( function_exists( 'add_settings_error' ) )
3261 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.' ) );
3265 case 'thumbnail_size_w':
3266 case 'thumbnail_size_h':
3267 case 'medium_size_w':
3268 case 'medium_size_h':
3269 case 'large_size_w':
3270 case 'large_size_h':
3271 case 'mailserver_port':
3272 case 'comment_max_links':
3273 case 'page_on_front':
3274 case 'page_for_posts':
3275 case 'rss_excerpt_length':
3276 case 'default_category':
3277 case 'default_email_category':
3278 case 'default_link_category':
3279 case 'close_comments_days_old':
3280 case 'comments_per_page':
3281 case 'thread_comments_depth':
3282 case 'users_can_register':
3283 case 'start_of_week':
3284 $value = absint( $value );
3287 case 'posts_per_page':
3288 case 'posts_per_rss':
3289 $value = (int) $value;
3290 if ( empty($value) )
3293 $value = abs($value);
3296 case 'default_ping_status':
3297 case 'default_comment_status':
3298 // Options that if not there have 0 value but need to be something like "closed"
3299 if ( $value == '0' || $value == '')
3303 case 'blogdescription':
3305 $value = wp_kses_post( $value );
3306 $value = esc_html( $value );
3309 case 'blog_charset':
3310 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3314 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3315 if ( null === $value )
3318 $value = intval( $value );
3323 case 'mailserver_url':
3324 case 'mailserver_login':
3325 case 'mailserver_pass':
3327 $value = strip_tags( $value );
3328 $value = wp_kses_data( $value );
3332 $value = explode( "\n", $value );
3333 $value = array_filter( array_map( 'trim', $value ) );
3334 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3335 $value = implode( "\n", $value );
3339 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3343 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3344 $value = esc_url_raw($value);
3346 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3347 if ( function_exists('add_settings_error') )
3348 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3353 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3354 $value = esc_url_raw($value);
3356 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3357 if ( function_exists('add_settings_error') )
3358 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3363 $allowed = get_available_languages();
3364 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3365 $allowed[] = WPLANG;
3367 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3368 $value = get_option( $option );
3372 case 'illegal_names':
3373 if ( ! is_array( $value ) )
3374 $value = explode( ' ', $value );
3376 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3382 case 'limited_email_domains':
3383 case 'banned_email_domains':
3384 if ( ! is_array( $value ) )
3385 $value = explode( "\n", $value );
3387 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3390 foreach ( $domains as $domain ) {
3391 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
3398 case 'timezone_string':
3399 $allowed_zones = timezone_identifiers_list();
3400 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3401 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3402 if ( function_exists('add_settings_error') )
3403 add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
3407 case 'permalink_structure':
3408 case 'category_base':
3410 $value = esc_url_raw( $value );
3411 $value = str_replace( 'http://', '', $value );
3414 case 'default_role' :
3415 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3416 $value = 'subscriber';
3419 case 'moderation_keys':
3420 case 'blacklist_keys':
3421 $value = explode( "\n", $value );
3422 $value = array_filter( array_map( 'trim', $value ) );
3423 $value = array_unique( $value );
3424 $value = implode( "\n", $value );
3429 * Filter an option value following sanitization.
3433 * @param string $value The sanitized option value.
3434 * @param string $option The option name.
3436 $value = apply_filters( "sanitize_option_{$option}", $value, $option );
3442 * Parses a string into variables to be stored in an array.
3444 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3445 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3449 * @param string $string The string to be parsed.
3450 * @param array $array Variables will be stored in this array.
3452 function wp_parse_str( $string, &$array ) {
3453 parse_str( $string, $array );
3454 if ( get_magic_quotes_gpc() )
3455 $array = stripslashes_deep( $array );
3457 * Filter the array of variables derived from a parsed string.
3461 * @param array $array The array populated with variables.
3463 $array = apply_filters( 'wp_parse_str', $array );
3467 * Convert lone less than signs.
3469 * KSES already converts lone greater than signs.
3471 * @uses wp_pre_kses_less_than_callback in the callback function.
3474 * @param string $text Text to be converted.
3475 * @return string Converted text.
3477 function wp_pre_kses_less_than( $text ) {
3478 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3482 * Callback function used by preg_replace.
3484 * @uses esc_html to format the $matches text.
3487 * @param array $matches Populated by matches to preg_replace.
3488 * @return string The text returned after esc_html if needed.
3490 function wp_pre_kses_less_than_callback( $matches ) {
3491 if ( false === strpos($matches[0], '>') )
3492 return esc_html($matches[0]);
3497 * WordPress implementation of PHP sprintf() with filters.
3500 * @link http://www.php.net/sprintf
3502 * @param string $pattern The string which formatted args are inserted.
3503 * @param mixed $args,... Arguments to be formatted into the $pattern string.
3504 * @return string The formatted string.
3506 function wp_sprintf( $pattern ) {
3507 $args = func_get_args();
3508 $len = strlen($pattern);
3512 while ( $len > $start ) {
3513 // Last character: append and break
3514 if ( strlen($pattern) - 1 == $start ) {
3515 $result .= substr($pattern, -1);
3519 // Literal %: append and continue
3520 if ( substr($pattern, $start, 2) == '%%' ) {
3526 // Get fragment before next %
3527 $end = strpos($pattern, '%', $start + 1);
3528 if ( false === $end )
3530 $fragment = substr($pattern, $start, $end - $start);
3532 // Fragment has a specifier
3533 if ( $pattern[$start] == '%' ) {
3534 // Find numbered arguments or take the next one in order
3535 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3536 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3537 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3540 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3544 * Filter a fragment from the pattern passed to wp_sprintf().
3546 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3550 * @param string $fragment A fragment from the pattern.
3551 * @param string $arg The argument.
3553 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3554 if ( $_fragment != $fragment )
3555 $fragment = $_fragment;
3557 $fragment = sprintf($fragment, strval($arg) );
3560 // Append to result and move to next fragment
3561 $result .= $fragment;
3568 * Localize list items before the rest of the content.
3570 * The '%l' must be at the first characters can then contain the rest of the
3571 * content. The list items will have ', ', ', and', and ' and ' added depending
3572 * on the amount of list items in the $args parameter.
3576 * @param string $pattern Content containing '%l' at the beginning.
3577 * @param array $args List items to prepend to the content and replace '%l'.
3578 * @return string Localized list items and rest of the content.
3580 function wp_sprintf_l($pattern, $args) {
3582 if ( substr($pattern, 0, 2) != '%l' )
3585 // Nothing to work with
3590 * Filter the translated delimiters used by wp_sprintf_l().
3591 * Placeholders (%s) are included to assist translators and then
3592 * removed before the array of strings reaches the filter.
3594 * Please note: Ampersands and entities should be avoided here.
3598 * @param array $delimiters An array of translated delimiters.
3600 $l = apply_filters( 'wp_sprintf_l', array(
3601 /* translators: used to join items in a list with more than 2 items */
3602 'between' => sprintf( __('%s, %s'), '', '' ),
3603 /* translators: used to join last two items in a list with more than 2 times */
3604 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3605 /* translators: used to join items in a list with only 2 items */
3606 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3609 $args = (array) $args;
3610 $result = array_shift($args);
3611 if ( count($args) == 1 )
3612 $result .= $l['between_only_two'] . array_shift($args);
3613 // Loop when more than two args
3616 $arg = array_shift($args);
3619 $result .= $l['between_last_two'] . $arg;
3621 $result .= $l['between'] . $arg;
3623 return $result . substr($pattern, 2);
3627 * Safely extracts not more than the first $count characters from html string.
3629 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3630 * be counted as one character. For example & will be counted as 4, < as
3635 * @param string $str String to get the excerpt from.
3636 * @param integer $count Maximum number of characters to take.
3637 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3638 * @return string The excerpt.
3640 function wp_html_excerpt( $str, $count, $more = null ) {
3641 if ( null === $more )
3643 $str = wp_strip_all_tags( $str, true );
3644 $excerpt = mb_substr( $str, 0, $count );
3645 // remove part of an entity at the end
3646 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3647 if ( $str != $excerpt )
3648 $excerpt = trim( $excerpt ) . $more;
3653 * Add a Base url to relative links in passed content.
3655 * By default it supports the 'src' and 'href' attributes. However this can be
3656 * changed via the 3rd param.
3660 * @param string $content String to search for links in.
3661 * @param string $base The base URL to prefix to links.
3662 * @param array $attrs The attributes which should be processed.
3663 * @return string The processed content.
3665 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3666 global $_links_add_base;
3667 $_links_add_base = $base;
3668 $attrs = implode('|', (array)$attrs);
3669 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3673 * Callback to add a base url to relative links in passed content.
3678 * @param string $m The matched link.
3679 * @return string The processed link.
3681 function _links_add_base($m) {
3682 global $_links_add_base;
3683 //1 = attribute name 2 = quotation mark 3 = URL
3684 return $m[1] . '=' . $m[2] .
3685 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3687 path_join( $_links_add_base, $m[3] ) )
3692 * Adds a Target attribute to all links in passed content.
3694 * This function by default only applies to <a> tags, however this can be
3695 * modified by the 3rd param.
3697 * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
3701 * @param string $content String to search for links in.
3702 * @param string $target The Target to add to the links.
3703 * @param array $tags An array of tags to apply to.
3704 * @return string The processed content.
3706 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3707 global $_links_add_target;
3708 $_links_add_target = $target;
3709 $tags = implode('|', (array)$tags);
3710 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
3714 * Callback to add a target attribute to all links in passed content.
3719 * @param string $m The matched link.
3720 * @return string The processed link.
3722 function _links_add_target( $m ) {
3723 global $_links_add_target;
3725 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
3726 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3730 * Normalize EOL characters and strip duplicate whitespace.
3734 * @param string $str The string to normalize.
3735 * @return string The normalized string.
3737 function normalize_whitespace( $str ) {
3738 $str = trim( $str );
3739 $str = str_replace( "\r", "\n", $str );
3740 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3745 * Properly strip all HTML tags including script and style
3747 * This differs from strip_tags() because it removes the contents of
3748 * the <script> and <style> tags. E.g. strip_tags( '<script>something</script>' )
3749 * will return 'something'. wp_strip_all_tags will return ''
3753 * @param string $string String containing HTML tags
3754 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3755 * @return string The processed string.
3757 function wp_strip_all_tags($string, $remove_breaks = false) {
3758 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3759 $string = strip_tags($string);
3761 if ( $remove_breaks )
3762 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3764 return trim( $string );
3768 * Sanitize a string from user input or from the db
3770 * check for invalid UTF-8,
3771 * Convert single < characters to entity,
3773 * remove line breaks, tabs and extra white space,
3778 * @param string $str
3781 function sanitize_text_field($str) {
3782 $filtered = wp_check_invalid_utf8( $str );
3784 if ( strpos($filtered, '<') !== false ) {
3785 $filtered = wp_pre_kses_less_than( $filtered );
3786 // This will strip extra whitespace for us.
3787 $filtered = wp_strip_all_tags( $filtered, true );
3789 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
3793 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
3794 $filtered = str_replace($match[0], '', $filtered);
3799 // Strip out the whitespace that may now exist after removing the octets.
3800 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
3804 * Filter a sanitized text field string.
3808 * @param string $filtered The sanitized string.
3809 * @param string $str The string prior to being sanitized.
3811 return apply_filters( 'sanitize_text_field', $filtered, $str );
3815 * i18n friendly version of basename()
3819 * @param string $path A path.
3820 * @param string $suffix If the filename ends in suffix this will also be cut off.
3823 function wp_basename( $path, $suffix = '' ) {
3824 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
3828 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
3830 * Violating our coding standards for a good function name.
3834 function capital_P_dangit( $text ) {
3835 // Simple replacement for titles
3836 $current_filter = current_filter();
3837 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
3838 return str_replace( 'Wordpress', 'WordPress', $text );
3839 // Still here? Use the more judicious replacement
3840 static $dblq = false;
3841 if ( false === $dblq )
3842 $dblq = _x( '“', 'opening curly double quote' );
3844 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
3845 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
3851 * Sanitize a mime type
3855 * @param string $mime_type Mime type
3856 * @return string Sanitized mime type
3858 function sanitize_mime_type( $mime_type ) {
3859 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3861 * Filter a mime type following sanitization.
3865 * @param string $sani_mime_type The sanitized mime type.
3866 * @param string $mime_type The mime type prior to sanitization.
3868 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
3872 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
3876 * @param string $to_ping Space or carriage return separated URLs
3877 * @return string URLs starting with the http or https protocol, separated by a carriage return.
3879 function sanitize_trackback_urls( $to_ping ) {
3880 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
3881 foreach ( $urls_to_ping as $k => $url ) {
3882 if ( !preg_match( '#^https?://.#i', $url ) )
3883 unset( $urls_to_ping[$k] );
3885 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
3886 $urls_to_ping = implode( "\n", $urls_to_ping );
3888 * Filter a list of trackback URLs following sanitization.
3890 * The string returned here consists of a space or carriage return-delimited list
3891 * of trackback URLs.
3895 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
3896 * @param string $to_ping Space or carriage return separated URLs before sanitization.
3898 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
3902 * Add slashes to a string or array of strings.
3904 * This should be used when preparing data for core API that expects slashed data.
3905 * This should not be used to escape data going directly into an SQL query.
3909 * @param string|array $value String or array of strings to slash.
3910 * @return string|array Slashed $value
3912 function wp_slash( $value ) {
3913 if ( is_array( $value ) ) {
3914 foreach ( $value as $k => $v ) {
3915 if ( is_array( $v ) ) {
3916 $value[$k] = wp_slash( $v );
3918 $value[$k] = addslashes( $v );
3922 $value = addslashes( $value );
3929 * Remove slashes from a string or array of strings.
3931 * This should be used to remove slashes from data passed to core API that
3932 * expects data to be unslashed.
3936 * @param string|array $value String or array of strings to unslash.
3937 * @return string|array Unslashed $value
3939 function wp_unslash( $value ) {
3940 return stripslashes_deep( $value );
3944 * Extract and return the first URL from passed content.
3948 * @param string $content A string which might contain a URL.
3949 * @return string The found URL.
3951 function get_url_in_content( $content ) {
3952 if ( empty( $content ) ) {
3956 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
3957 return esc_url_raw( $matches[2] );
3964 * Returns the regexp for common whitespace characters.
3966 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
3967 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
3968 * sequence was found to be unreliable due to random inclusion of the A0 byte.
3972 * @return string The spaces regexp.
3974 function wp_spaces_regexp() {
3977 if ( empty( $spaces ) ) {
3979 * Filter the regexp for common whitespace characters.
3981 * This string is substituted for the \s sequence as needed in regular
3982 * expressions. For websites not written in English, different characters
3983 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
3984 * sequence may not be in use.
3988 * @param string $spaces Regexp pattern for matching common whitespace characters.
3990 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );