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.
23 * Do not use this function before the 'init' action hook; everything will break.
27 * @global array $wp_cockneyreplace Array of formatted entities for certain common phrases
28 * @global array $shortcode_tags
29 * @staticvar array $static_characters
30 * @staticvar array $static_replacements
31 * @staticvar array $dynamic_characters
32 * @staticvar array $dynamic_replacements
33 * @staticvar array $default_no_texturize_tags
34 * @staticvar array $default_no_texturize_shortcodes
35 * @staticvar bool $run_texturize
37 * @param string $text The text to be formatted
38 * @param bool $reset Set to true for unit testing. Translated patterns will reset.
39 * @return string The string replaced with html entities
41 function wptexturize( $text, $reset = false ) {
42 global $wp_cockneyreplace, $shortcode_tags;
43 static $static_characters = null,
44 $static_replacements = null,
45 $dynamic_characters = null,
46 $dynamic_replacements = null,
47 $default_no_texturize_tags = null,
48 $default_no_texturize_shortcodes = null,
49 $run_texturize = true,
53 $opening_quote = null,
54 $closing_quote = null,
55 $opening_single_quote = null,
56 $closing_single_quote = null,
57 $open_q_flag = '<!--oq-->',
58 $open_sq_flag = '<!--osq-->',
59 $apos_flag = '<!--apos-->';
61 // If there's nothing to do, just stop.
62 if ( empty( $text ) || false === $run_texturize ) {
66 // Set up static variables. Run once only.
67 if ( $reset || ! isset( $static_characters ) ) {
69 * Filter whether to skip running wptexturize().
71 * Passing false to the filter will effectively short-circuit wptexturize().
72 * returning the original text passed to the function instead.
74 * The filter runs only once, the first time wptexturize() is called.
80 * @param bool $run_texturize Whether to short-circuit wptexturize().
82 $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
83 if ( false === $run_texturize ) {
87 /* translators: opening curly double quote */
88 $opening_quote = _x( '“', 'opening curly double quote' );
89 /* translators: closing curly double quote */
90 $closing_quote = _x( '”', 'closing curly double quote' );
92 /* translators: apostrophe, for example in 'cause or can't */
93 $apos = _x( '’', 'apostrophe' );
95 /* translators: prime, for example in 9' (nine feet) */
96 $prime = _x( '′', 'prime' );
97 /* translators: double prime, for example in 9" (nine inches) */
98 $double_prime = _x( '″', 'double prime' );
100 /* translators: opening curly single quote */
101 $opening_single_quote = _x( '‘', 'opening curly single quote' );
102 /* translators: closing curly single quote */
103 $closing_single_quote = _x( '’', 'closing curly single quote' );
105 /* translators: en dash */
106 $en_dash = _x( '–', 'en dash' );
107 /* translators: em dash */
108 $em_dash = _x( '—', 'em dash' );
110 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
111 $default_no_texturize_shortcodes = array('code');
113 // if a plugin has provided an autocorrect array, use it
114 if ( isset($wp_cockneyreplace) ) {
115 $cockney = array_keys( $wp_cockneyreplace );
116 $cockneyreplace = array_values( $wp_cockneyreplace );
118 /* translators: This is a comma-separated list of words that defy the syntax of quotations in normal use,
119 * for example... 'We do not have enough words yet' ... is a typical quoted phrase. But when we write
120 * lines of code 'til we have enough of 'em, then we need to insert apostrophes instead of quotes.
122 $cockney = explode( ',', _x( "'tain't,'twere,'twas,'tis,'twill,'til,'bout,'nuff,'round,'cause,'em",
123 'Comma-separated list of words to texturize in your language' ) );
125 $cockneyreplace = explode( ',', _x( '’tain’t,’twere,’twas,’tis,’twill,’til,’bout,’nuff,’round,’cause,’em',
126 'Comma-separated list of replacement words in your language' ) );
129 $static_characters = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
130 $static_replacements = array_merge( array( '…', $opening_quote, $closing_quote, ' ™' ), $cockneyreplace );
133 // Pattern-based replacements of characters.
134 // Sort the remaining patterns into several arrays for performance tuning.
135 $dynamic_characters = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
136 $dynamic_replacements = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
138 $spaces = wp_spaces_regexp();
140 // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
141 if ( "'" !== $apos || "'" !== $closing_single_quote ) {
142 $dynamic[ '/\'(\d\d)\'(?=\Z|[.,:;!?)}\-\]]|>|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_single_quote;
144 if ( "'" !== $apos || '"' !== $closing_quote ) {
145 $dynamic[ '/\'(\d\d)"(?=\Z|[.,:;!?)}\-\]]|>|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_quote;
148 // '99 '99s '99's (apostrophe) But never '9 or '99% or '999 or '99.0.
149 if ( "'" !== $apos ) {
150 $dynamic[ '/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/' ] = $apos_flag;
153 // Quoted Numbers like '0.42'
154 if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
155 $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $open_sq_flag . '$1' . $closing_single_quote;
158 // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
159 if ( "'" !== $opening_single_quote ) {
160 $dynamic[ '/(?<=\A|[([{"\-]|<|' . $spaces . ')\'/' ] = $open_sq_flag;
163 // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
164 if ( "'" !== $apos ) {
165 $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;!?"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos_flag;
168 $dynamic_characters['apos'] = array_keys( $dynamic );
169 $dynamic_replacements['apos'] = array_values( $dynamic );
172 // Quoted Numbers like "42"
173 if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
174 $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $open_q_flag . '$1' . $closing_quote;
177 // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
178 if ( '"' !== $opening_quote ) {
179 $dynamic[ '/(?<=\A|[([{\-]|<|' . $spaces . ')"(?!' . $spaces . ')/' ] = $open_q_flag;
182 $dynamic_characters['quote'] = array_keys( $dynamic );
183 $dynamic_replacements['quote'] = array_values( $dynamic );
187 $dynamic[ '/---/' ] = $em_dash;
188 $dynamic[ '/(?<=^|' . $spaces . ')--(?=$|' . $spaces . ')/' ] = $em_dash;
189 $dynamic[ '/(?<!xn)--/' ] = $en_dash;
190 $dynamic[ '/(?<=^|' . $spaces . ')-(?=$|' . $spaces . ')/' ] = $en_dash;
192 $dynamic_characters['dash'] = array_keys( $dynamic );
193 $dynamic_replacements['dash'] = array_values( $dynamic );
196 // Must do this every time in case plugins use these filters in a context sensitive manner
198 * Filter the list of HTML elements not to texturize.
202 * @param array $default_no_texturize_tags An array of HTML element names.
204 $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
206 * Filter the list of shortcodes not to texturize.
210 * @param array $default_no_texturize_shortcodes An array of shortcode names.
212 $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
214 $no_texturize_tags_stack = array();
215 $no_texturize_shortcodes_stack = array();
217 // Look for shortcodes and HTML elements.
219 preg_match_all( '@\[/?([^<>&/\[\]\x00-\x20=]++)@', $text, $matches );
220 $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
221 $found_shortcodes = ! empty( $tagnames );
222 $shortcode_regex = $found_shortcodes ? _get_wptexturize_shortcode_regex( $tagnames ) : '';
223 $regex = _get_wptexturize_split_regex( $shortcode_regex );
225 $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
227 foreach ( $textarr as &$curl ) {
228 // Only call _wptexturize_pushpop_element if $curl is a delimiter.
230 if ( '<' === $first ) {
231 if ( '<!--' === substr( $curl, 0, 4 ) ) {
232 // This is an HTML comment delimiter.
235 // This is an HTML element delimiter.
237 // Replace each & with & unless it already looks like an entity.
238 $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $curl );
240 _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
243 } elseif ( '' === trim( $curl ) ) {
244 // This is a newline between delimiters. Performance improves when we check this.
247 } elseif ( '[' === $first && $found_shortcodes && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
248 // This is a shortcode delimiter.
250 if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
251 // Looks like a normal shortcode.
252 _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
254 // Looks like an escaped shortcode.
258 } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
259 // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
261 $curl = str_replace( $static_characters, $static_replacements, $curl );
263 if ( false !== strpos( $curl, "'" ) ) {
264 $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
265 $curl = wptexturize_primes( $curl, "'", $prime, $open_sq_flag, $closing_single_quote );
266 $curl = str_replace( $apos_flag, $apos, $curl );
267 $curl = str_replace( $open_sq_flag, $opening_single_quote, $curl );
269 if ( false !== strpos( $curl, '"' ) ) {
270 $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
271 $curl = wptexturize_primes( $curl, '"', $double_prime, $open_q_flag, $closing_quote );
272 $curl = str_replace( $open_q_flag, $opening_quote, $curl );
274 if ( false !== strpos( $curl, '-' ) ) {
275 $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
278 // 9x9 (times), but never 0x9999
279 if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
280 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
281 $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1×$2', $curl );
284 // Replace each & with & unless it already looks like an entity.
285 $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $curl );
289 return implode( '', $textarr );
293 * Implements a logic tree to determine whether or not "7'." represents seven feet,
294 * then converts the special char into either a prime char or a closing quote char.
298 * @param string $haystack The plain text to be searched.
299 * @param string $needle The character to search for such as ' or ".
300 * @param string $prime The prime char to use for replacement.
301 * @param string $open_quote The opening quote char. Opening quote replacement must be
302 * accomplished already.
303 * @param string $close_quote The closing quote char to use for replacement.
304 * @return string The $haystack value after primes and quotes replacements.
306 function wptexturize_primes( $haystack, $needle, $prime, $open_quote, $close_quote ) {
307 $spaces = wp_spaces_regexp();
308 $flag = '<!--wp-prime-or-quote-->';
309 $quote_pattern = "/$needle(?=\\Z|[.,:;!?)}\\-\\]]|>|" . $spaces . ")/";
310 $prime_pattern = "/(?<=\\d)$needle/";
311 $flag_after_digit = "/(?<=\\d)$flag/";
312 $flag_no_digit = "/(?<!\\d)$flag/";
314 $sentences = explode( $open_quote, $haystack );
316 foreach ( $sentences as $key => &$sentence ) {
317 if ( false === strpos( $sentence, $needle ) ) {
319 } elseif ( 0 !== $key && 0 === substr_count( $sentence, $close_quote ) ) {
320 $sentence = preg_replace( $quote_pattern, $flag, $sentence, -1, $count );
322 // This sentence appears to have multiple closing quotes. Attempt Vulcan logic.
323 $sentence = preg_replace( $flag_no_digit, $close_quote, $sentence, -1, $count2 );
324 if ( 0 === $count2 ) {
325 // Try looking for a quote followed by a period.
326 $count2 = substr_count( $sentence, "$flag." );
328 // Assume the rightmost quote-period match is the end of quotation.
329 $pos = strrpos( $sentence, "$flag." );
331 // When all else fails, make the rightmost candidate a closing quote.
332 // This is most likely to be problematic in the context of bug #18549.
333 $pos = strrpos( $sentence, $flag );
335 $sentence = substr_replace( $sentence, $close_quote, $pos, strlen( $flag ) );
337 // Use conventional replacement on any remaining primes and quotes.
338 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
339 $sentence = preg_replace( $flag_after_digit, $prime, $sentence );
340 $sentence = str_replace( $flag, $close_quote, $sentence );
341 } elseif ( 1 == $count ) {
342 // Found only one closing quote candidate, so give it priority over primes.
343 $sentence = str_replace( $flag, $close_quote, $sentence );
344 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
346 // No closing quotes found. Just run primes pattern.
347 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
350 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
351 $sentence = preg_replace( $quote_pattern, $close_quote, $sentence );
353 if ( '"' == $needle && false !== strpos( $sentence, '"' ) ) {
354 $sentence = str_replace( '"', $close_quote, $sentence );
358 return implode( $open_quote, $sentences );
362 * Search for disabled element tags. Push element to stack on tag open and pop
365 * Assumes first char of $text is tag opening and last char is tag closing.
366 * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
371 * @param string $text Text to check. Must be a tag like `<html>` or `[shortcode]`.
372 * @param array $stack List of open tag elements.
373 * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
375 function _wptexturize_pushpop_element( $text, &$stack, $disabled_elements ) {
376 // Is it an opening tag or closing tag?
377 if ( isset( $text[1] ) && '/' !== $text[1] ) {
380 } elseif ( 0 == count( $stack ) ) {
381 // Stack is empty. Just stop.
384 $opening_tag = false;
388 // Parse out the tag name.
389 $space = strpos( $text, ' ' );
390 if ( false === $space ) {
393 $space -= $name_offset;
395 $tag = substr( $text, $name_offset, $space );
397 // Handle disabled tags.
398 if ( in_array( $tag, $disabled_elements ) ) {
399 if ( $opening_tag ) {
401 * This disables texturize until we find a closing tag of our type
402 * (e.g. <pre>) even if there was invalid nesting before that
404 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
405 * "baba" won't be texturize
408 array_push( $stack, $tag );
409 } elseif ( end( $stack ) == $tag ) {
416 * Replaces double line-breaks with paragraph elements.
418 * A group of regex replaces used to identify text formatted with newlines and
419 * replace double line-breaks with HTML paragraph tags. The remaining line-breaks
420 * after conversion become <<br />> tags, unless $br is set to '0' or 'false'.
424 * @param string $pee The text which has to be formatted.
425 * @param bool $br Optional. If set, this will convert all remaining line-breaks
426 * after paragraphing. Default true.
427 * @return string Text which has been converted into correct paragraph tags.
429 function wpautop( $pee, $br = true ) {
432 if ( trim($pee) === '' )
435 // Just to make things a little easier, pad the end.
439 * Pre tags shouldn't be touched by autop.
440 * Replace pre tags with placeholders and bring them back after autop.
442 if ( strpos($pee, '<pre') !== false ) {
443 $pee_parts = explode( '</pre>', $pee );
444 $last_pee = array_pop($pee_parts);
448 foreach ( $pee_parts as $pee_part ) {
449 $start = strpos($pee_part, '<pre');
452 if ( $start === false ) {
457 $name = "<pre wp-pre-tag-$i></pre>";
458 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
460 $pee .= substr( $pee_part, 0, $start ) . $name;
466 // Change multiple <br>s into two line breaks, which will turn into paragraphs.
467 $pee = preg_replace('|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee);
469 $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|figcaption|details|menu|summary)';
471 // Add a single line break above block-level opening tags.
472 $pee = preg_replace('!(<' . $allblocks . '[\s/>])!', "\n$1", $pee);
474 // Add a double line break below block-level closing tags.
475 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
477 // Standardize newline characters to "\n".
478 $pee = str_replace(array("\r\n", "\r"), "\n", $pee);
480 // Find newlines in all elements and add placeholders.
481 $pee = wp_replace_in_html_tags( $pee, array( "\n" => " <!-- wpnl --> " ) );
483 // Collapse line breaks before and after <option> elements so they don't get autop'd.
484 if ( strpos( $pee, '<option' ) !== false ) {
485 $pee = preg_replace( '|\s*<option|', '<option', $pee );
486 $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
490 * Collapse line breaks inside <object> elements, before <param> and <embed> elements
491 * so they don't get autop'd.
493 if ( strpos( $pee, '</object>' ) !== false ) {
494 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
495 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
496 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
500 * Collapse line breaks inside <audio> and <video> elements,
501 * before and after <source> and <track> elements.
503 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
504 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
505 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
506 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
509 // Remove more than two contiguous line breaks.
510 $pee = preg_replace("/\n\n+/", "\n\n", $pee);
512 // Split up the contents into an array of strings, separated by double line breaks.
513 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
515 // Reset $pee prior to rebuilding.
518 // Rebuild the content as a string, wrapping every bit with a <p>.
519 foreach ( $pees as $tinkle ) {
520 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
523 // Under certain strange conditions it could create a P of entirely whitespace.
524 $pee = preg_replace('|<p>\s*</p>|', '', $pee);
526 // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
527 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
529 // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
530 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
532 // In some cases <li> may get wrapped in <p>, fix them.
533 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee);
535 // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
536 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
537 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
539 // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
540 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
542 // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
543 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
545 // Optionally insert line breaks.
547 // Replace newlines that shouldn't be touched with a placeholder.
548 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
551 $pee = str_replace( array( '<br>', '<br/>' ), '<br />', $pee );
553 // Replace any new line characters that aren't preceded by a <br /> with a <br />.
554 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee);
556 // Replace newline placeholders with newlines.
557 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
560 // If a <br /> tag is after an opening or closing block tag, remove it.
561 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
563 // If a <br /> tag is before a subset of opening or closing block tags, remove it.
564 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
565 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
567 // Replace placeholder <pre> tags with their original content.
568 if ( !empty($pre_tags) )
569 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
571 // Restore newlines in all elements.
572 if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
573 $pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
580 * Separate HTML elements and comments from the text.
584 * @param string $input The text which has to be formatted.
585 * @return array The formatted text.
587 function wp_html_split( $input ) {
588 return preg_split( get_html_split_regex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE );
592 * Retrieve the regular expression for an HTML element.
596 * @return string The regular expression
598 function get_html_split_regex() {
601 if ( ! isset( $regex ) ) {
603 '!' // Start of comment, after the <.
604 . '(?:' // Unroll the loop: Consume everything until --> is found.
605 . '-(?!->)' // Dash not followed by end of comment.
606 . '[^\-]*+' // Consume non-dashes.
607 . ')*+' // Loop possessively.
608 . '(?:-->)?'; // End of comment. If not found, match all input.
611 '!\[CDATA\[' // Start of comment, after the <.
612 . '[^\]]*+' // Consume non-].
613 . '(?:' // Unroll the loop: Consume everything until ]]> is found.
614 . '](?!]>)' // One ] not followed by end of comment.
615 . '[^\]]*+' // Consume non-].
616 . ')*+' // Loop possessively.
617 . '(?:]]>)?'; // End of comment. If not found, match all input.
620 '(?=' // Is the element escaped?
625 . '(?(?=!-)' // If yes, which type?
632 '/(' // Capture the entire match.
633 . '<' // Find start of element.
634 . '(?' // Conditional expression follows.
635 . $escaped // Find end of escaped element.
636 . '|' // ... else ...
637 . '[^>]*>?' // Find end of normal element.
646 * Retrieve the combined regular expression for HTML and shortcodes.
650 * @internal This function will be removed in 4.5.0 per Shortcode API Roadmap.
653 * @param string $shortcode_regex The result from _get_wptexturize_shortcode_regex(). Optional.
654 * @return string The regular expression
656 function _get_wptexturize_split_regex( $shortcode_regex = '' ) {
659 if ( ! isset( $html_regex ) ) {
661 '!' // Start of comment, after the <.
662 . '(?:' // Unroll the loop: Consume everything until --> is found.
663 . '-(?!->)' // Dash not followed by end of comment.
664 . '[^\-]*+' // Consume non-dashes.
665 . ')*+' // Loop possessively.
666 . '(?:-->)?'; // End of comment. If not found, match all input.
668 $html_regex = // Needs replaced with wp_html_split() per Shortcode API Roadmap.
669 '<' // Find start of element.
670 . '(?(?=!--)' // Is this a comment?
671 . $comment_regex // Find end of comment.
673 . '[^>]*>?' // Find end of element. If not found, match all input.
677 if ( empty( $shortcode_regex ) ) {
678 $regex = '/(' . $html_regex . ')/';
680 $regex = '/(' . $html_regex . '|' . $shortcode_regex . ')/';
687 * Retrieve the regular expression for shortcodes.
691 * @internal This function will be removed in 4.5.0 per Shortcode API Roadmap.
694 * @param array $tagnames List of shortcodes to find.
695 * @return string The regular expression
697 function _get_wptexturize_shortcode_regex( $tagnames ) {
698 $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
699 $tagregexp = "(?:$tagregexp)(?=[\\s\\]\\/])"; // Excerpt of get_shortcode_regex().
701 '\[' // Find start of shortcode.
702 . '[\/\[]?' // Shortcodes may begin with [/ or [[
703 . $tagregexp // Only match registered shortcodes, because performance.
705 . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
707 . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
708 . ')*+' // Possessive critical.
709 . '\]' // Find end of shortcode.
710 . '\]?'; // Shortcodes may end with ]]
716 * Replace characters or phrases within HTML elements only.
720 * @param string $haystack The text which has to be formatted.
721 * @param array $replace_pairs In the form array('from' => 'to', ...).
722 * @return string The formatted text.
724 function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
725 // Find all elements.
726 $textarr = wp_html_split( $haystack );
729 // Optimize when searching for one item.
730 if ( 1 === count( $replace_pairs ) ) {
731 // Extract $needle and $replace.
732 foreach ( $replace_pairs as $needle => $replace );
734 // Loop through delimiters (elements) only.
735 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
736 if ( false !== strpos( $textarr[$i], $needle ) ) {
737 $textarr[$i] = str_replace( $needle, $replace, $textarr[$i] );
742 // Extract all $needles.
743 $needles = array_keys( $replace_pairs );
745 // Loop through delimiters (elements) only.
746 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
747 foreach ( $needles as $needle ) {
748 if ( false !== strpos( $textarr[$i], $needle ) ) {
749 $textarr[$i] = strtr( $textarr[$i], $replace_pairs );
751 // After one strtr() break out of the foreach loop and look at next element.
759 $haystack = implode( $textarr );
766 * Newline preservation help function for wpautop
771 * @param array $matches preg_replace_callback matches array
774 function _autop_newline_preservation_helper( $matches ) {
775 return str_replace( "\n", "<WPPreserveNewline />", $matches[0] );
779 * Don't auto-p wrap shortcodes that stand alone
781 * Ensures that shortcodes are not wrapped in `<p>...</p>`.
785 * @global array $shortcode_tags
787 * @param string $pee The content.
788 * @return string The filtered content.
790 function shortcode_unautop( $pee ) {
791 global $shortcode_tags;
793 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
797 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
798 $spaces = wp_spaces_regexp();
802 . '<p>' // Opening paragraph
803 . '(?:' . $spaces . ')*+' // Optional leading whitespace
804 . '(' // 1: The shortcode
805 . '\\[' // Opening bracket
806 . "($tagregexp)" // 2: Shortcode name
807 . '(?![\\w-])' // Not followed by word character or hyphen
808 // Unroll the loop: Inside the opening shortcode tag
809 . '[^\\]\\/]*' // Not a closing bracket or forward slash
811 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
812 . '[^\\]\\/]*' // Not a closing bracket or forward slash
815 . '\\/\\]' // Self closing tag and closing bracket
817 . '\\]' // Closing bracket
818 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
819 . '[^\\[]*+' // Not an opening bracket
821 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
822 . '[^\\[]*+' // Not an opening bracket
824 . '\\[\\/\\2\\]' // Closing shortcode tag
828 . '(?:' . $spaces . ')*+' // optional trailing whitespace
829 . '<\\/p>' // closing paragraph
832 return preg_replace( $pattern, '$1', $pee );
836 * Checks to see if a string is utf8 encoded.
838 * NOTE: This function checks for 5-Byte sequences, UTF8
839 * has Bytes Sequences with a maximum length of 4.
841 * @author bmorel at ssi dot fr (modified)
844 * @param string $str The string to be checked
845 * @return bool True if $str fits a UTF-8 model, false otherwise.
847 function seems_utf8( $str ) {
848 mbstring_binary_safe_encoding();
849 $length = strlen($str);
850 reset_mbstring_encoding();
851 for ($i=0; $i < $length; $i++) {
853 if ($c < 0x80) $n = 0; // 0bbbbbbb
854 elseif (($c & 0xE0) == 0xC0) $n=1; // 110bbbbb
855 elseif (($c & 0xF0) == 0xE0) $n=2; // 1110bbbb
856 elseif (($c & 0xF8) == 0xF0) $n=3; // 11110bbb
857 elseif (($c & 0xFC) == 0xF8) $n=4; // 111110bb
858 elseif (($c & 0xFE) == 0xFC) $n=5; // 1111110b
859 else return false; // Does not match any model
860 for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
861 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
869 * Converts a number of special characters into their HTML entities.
871 * Specifically deals with: &, <, >, ", and '.
873 * $quote_style can be set to ENT_COMPAT to encode " to
874 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
879 * @staticvar string $_charset
881 * @param string $string The text which is to be encoded.
882 * @param int|string $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
883 * both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES.
884 * Also compatible with old values; converting single quotes if set to 'single',
885 * double if set to 'double' or both if otherwise set.
886 * Default is ENT_NOQUOTES.
887 * @param string $charset Optional. The character encoding of the string. Default is false.
888 * @param bool $double_encode Optional. Whether to encode existing html entities. Default is false.
889 * @return string The encoded text with HTML entities.
891 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
892 $string = (string) $string;
894 if ( 0 === strlen( $string ) )
897 // Don't bother if there are no specialchars - saves some processing
898 if ( ! preg_match( '/[&<>"\']/', $string ) )
901 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
902 if ( empty( $quote_style ) )
903 $quote_style = ENT_NOQUOTES;
904 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
905 $quote_style = ENT_QUOTES;
907 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
909 static $_charset = null;
910 if ( ! isset( $_charset ) ) {
911 $alloptions = wp_load_alloptions();
912 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
914 $charset = $_charset;
917 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
920 $_quote_style = $quote_style;
922 if ( $quote_style === 'double' ) {
923 $quote_style = ENT_COMPAT;
924 $_quote_style = ENT_COMPAT;
925 } elseif ( $quote_style === 'single' ) {
926 $quote_style = ENT_NOQUOTES;
929 if ( ! $double_encode ) {
930 // Guarantee every &entity; is valid, convert &garbage; into &garbage;
931 // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
932 $string = wp_kses_normalize_entities( $string );
935 $string = @htmlspecialchars( $string, $quote_style, $charset, $double_encode );
937 // Backwards compatibility
938 if ( 'single' === $_quote_style )
939 $string = str_replace( "'", ''', $string );
945 * Converts a number of HTML entities into their special characters.
947 * Specifically deals with: &, <, >, ", and '.
949 * $quote_style can be set to ENT_COMPAT to decode " entities,
950 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
954 * @param string $string The text which is to be decoded.
955 * @param string|int $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
956 * both single and double if set to ENT_QUOTES or
957 * none if set to ENT_NOQUOTES.
958 * Also compatible with old _wp_specialchars() values;
959 * converting single quotes if set to 'single',
960 * double if set to 'double' or both if otherwise set.
961 * Default is ENT_NOQUOTES.
962 * @return string The decoded text without HTML entities.
964 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
965 $string = (string) $string;
967 if ( 0 === strlen( $string ) ) {
971 // Don't bother if there are no entities - saves a lot of processing
972 if ( strpos( $string, '&' ) === false ) {
976 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
977 if ( empty( $quote_style ) ) {
978 $quote_style = ENT_NOQUOTES;
979 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
980 $quote_style = ENT_QUOTES;
983 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
984 $single = array( ''' => '\'', ''' => '\'' );
985 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
986 $double = array( '"' => '"', '"' => '"', '"' => '"' );
987 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
988 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
989 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
991 if ( $quote_style === ENT_QUOTES ) {
992 $translation = array_merge( $single, $double, $others );
993 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
994 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
995 $translation = array_merge( $double, $others );
996 $translation_preg = array_merge( $double_preg, $others_preg );
997 } elseif ( $quote_style === 'single' ) {
998 $translation = array_merge( $single, $others );
999 $translation_preg = array_merge( $single_preg, $others_preg );
1000 } elseif ( $quote_style === ENT_NOQUOTES ) {
1001 $translation = $others;
1002 $translation_preg = $others_preg;
1005 // Remove zero padding on numeric entities
1006 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
1008 // Replace characters according to translation table
1009 return strtr( $string, $translation );
1013 * Checks for invalid UTF8 in a string.
1017 * @staticvar bool $is_utf8
1018 * @staticvar bool $utf8_pcre
1020 * @param string $string The text which is to be checked.
1021 * @param bool $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
1022 * @return string The checked text.
1024 function wp_check_invalid_utf8( $string, $strip = false ) {
1025 $string = (string) $string;
1027 if ( 0 === strlen( $string ) ) {
1031 // Store the site charset as a static to avoid multiple calls to get_option()
1032 static $is_utf8 = null;
1033 if ( ! isset( $is_utf8 ) ) {
1034 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
1040 // Check for support for utf8 in the installed PCRE library once and store the result in a static
1041 static $utf8_pcre = null;
1042 if ( ! isset( $utf8_pcre ) ) {
1043 $utf8_pcre = @preg_match( '/^./u', 'a' );
1045 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
1046 if ( !$utf8_pcre ) {
1050 // preg_match fails when it encounters invalid UTF8 in $string
1051 if ( 1 === @preg_match( '/^./us', $string ) ) {
1055 // Attempt to strip the bad chars if requested (not recommended)
1056 if ( $strip && function_exists( 'iconv' ) ) {
1057 return iconv( 'utf-8', 'utf-8', $string );
1064 * Encode the Unicode values to be used in the URI.
1068 * @param string $utf8_string
1069 * @param int $length Max length of the string
1070 * @return string String with Unicode encoded for URI.
1072 function utf8_uri_encode( $utf8_string, $length = 0 ) {
1076 $unicode_length = 0;
1078 mbstring_binary_safe_encoding();
1079 $string_length = strlen( $utf8_string );
1080 reset_mbstring_encoding();
1082 for ($i = 0; $i < $string_length; $i++ ) {
1084 $value = ord( $utf8_string[ $i ] );
1086 if ( $value < 128 ) {
1087 if ( $length && ( $unicode_length >= $length ) )
1089 $unicode .= chr($value);
1092 if ( count( $values ) == 0 ) {
1093 if ( $value < 224 ) {
1095 } elseif ( $value < 240 ) {
1104 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
1106 if ( count( $values ) == $num_octets ) {
1107 for ( $j = 0; $j < $num_octets; $j++ ) {
1108 $unicode .= '%' . dechex( $values[ $j ] );
1111 $unicode_length += $num_octets * 3;
1123 * Converts all accent characters to ASCII characters.
1125 * If there are no accent characters, then the string given is just returned.
1129 * @param string $string Text that might have accent characters
1130 * @return string Filtered string with replaced "nice" characters.
1132 function remove_accents( $string ) {
1133 if ( !preg_match('/[\x80-\xff]/', $string) )
1136 if (seems_utf8($string)) {
1138 // Decompositions for Latin-1 Supplement
1139 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
1140 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
1141 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
1142 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
1143 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
1144 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
1145 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
1146 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
1147 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
1148 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
1149 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
1150 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
1151 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
1152 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
1153 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
1154 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
1155 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
1156 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
1157 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
1158 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
1159 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
1160 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
1161 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
1162 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
1163 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
1164 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
1165 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
1166 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
1167 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
1168 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
1169 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
1170 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
1171 // Decompositions for Latin Extended-A
1172 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
1173 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
1174 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
1175 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
1176 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
1177 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
1178 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
1179 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
1180 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
1181 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
1182 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
1183 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
1184 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
1185 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
1186 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
1187 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
1188 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
1189 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
1190 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
1191 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
1192 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
1193 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
1194 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
1195 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
1196 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
1197 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
1198 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
1199 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
1200 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
1201 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
1202 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
1203 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
1204 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
1205 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
1206 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
1207 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
1208 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
1209 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
1210 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
1211 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
1212 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
1213 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
1214 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
1215 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
1216 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
1217 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
1218 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
1219 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
1220 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
1221 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
1222 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
1223 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
1224 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
1225 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
1226 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
1227 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
1228 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
1229 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
1230 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
1231 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
1232 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
1233 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
1234 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
1235 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
1236 // Decompositions for Latin Extended-B
1237 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
1238 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
1240 chr(226).chr(130).chr(172) => 'E',
1242 chr(194).chr(163) => '',
1243 // Vowels with diacritic (Vietnamese)
1245 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
1246 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
1248 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
1249 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
1250 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
1251 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
1252 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
1253 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
1254 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
1256 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
1257 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
1258 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
1259 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
1260 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
1261 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
1262 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
1263 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
1264 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
1265 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
1266 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
1267 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
1269 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
1270 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
1271 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
1272 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
1273 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
1274 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
1275 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
1276 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
1278 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
1279 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
1280 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
1281 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
1282 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
1283 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
1285 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
1286 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
1287 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
1288 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
1289 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
1290 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
1291 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
1292 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
1293 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
1294 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
1295 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
1296 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
1297 // Vowels with diacritic (Chinese, Hanyu Pinyin)
1298 chr(201).chr(145) => 'a',
1300 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
1302 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
1304 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
1305 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
1306 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
1307 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
1308 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
1310 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
1313 // Used for locale-specific rules
1314 $locale = get_locale();
1316 if ( 'de_DE' == $locale || 'de_DE_formal' == $locale ) {
1317 $chars[ chr(195).chr(132) ] = 'Ae';
1318 $chars[ chr(195).chr(164) ] = 'ae';
1319 $chars[ chr(195).chr(150) ] = 'Oe';
1320 $chars[ chr(195).chr(182) ] = 'oe';
1321 $chars[ chr(195).chr(156) ] = 'Ue';
1322 $chars[ chr(195).chr(188) ] = 'ue';
1323 $chars[ chr(195).chr(159) ] = 'ss';
1324 } elseif ( 'da_DK' === $locale ) {
1325 $chars[ chr(195).chr(134) ] = 'Ae';
1326 $chars[ chr(195).chr(166) ] = 'ae';
1327 $chars[ chr(195).chr(152) ] = 'Oe';
1328 $chars[ chr(195).chr(184) ] = 'oe';
1329 $chars[ chr(195).chr(133) ] = 'Aa';
1330 $chars[ chr(195).chr(165) ] = 'aa';
1333 $string = strtr($string, $chars);
1336 // Assume ISO-8859-1 if not UTF-8
1337 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1338 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1339 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1340 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1341 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1342 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1343 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1344 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1345 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1346 .chr(252).chr(253).chr(255);
1348 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1350 $string = strtr($string, $chars['in'], $chars['out']);
1351 $double_chars = array();
1352 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1353 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1354 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1361 * Sanitizes a filename, replacing whitespace with dashes.
1363 * Removes special characters that are illegal in filenames on certain
1364 * operating systems and special characters requiring special escaping
1365 * to manipulate at the command line. Replaces spaces and consecutive
1366 * dashes with a single dash. Trims period, dash and underscore from beginning
1367 * and end of filename.
1371 * @param string $filename The filename to be sanitized
1372 * @return string The sanitized filename
1374 function sanitize_file_name( $filename ) {
1375 $filename_raw = $filename;
1376 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0));
1378 * Filter the list of characters to remove from a filename.
1382 * @param array $special_chars Characters to remove.
1383 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1385 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1386 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1387 $filename = str_replace( $special_chars, '', $filename );
1388 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1389 $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
1390 $filename = trim( $filename, '.-_' );
1392 // Split the filename into a base and extension[s]
1393 $parts = explode('.', $filename);
1395 // Return if only one extension
1396 if ( count( $parts ) <= 2 ) {
1398 * Filter a sanitized filename string.
1402 * @param string $filename Sanitized filename.
1403 * @param string $filename_raw The filename prior to sanitization.
1405 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1408 // Process multiple extensions
1409 $filename = array_shift($parts);
1410 $extension = array_pop($parts);
1411 $mimes = get_allowed_mime_types();
1414 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1415 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1417 foreach ( (array) $parts as $part) {
1418 $filename .= '.' . $part;
1420 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1422 foreach ( $mimes as $ext_preg => $mime_match ) {
1423 $ext_preg = '!^(' . $ext_preg . ')$!i';
1424 if ( preg_match( $ext_preg, $part ) ) {
1433 $filename .= '.' . $extension;
1434 /** This filter is documented in wp-includes/formatting.php */
1435 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1439 * Sanitizes a username, stripping out unsafe characters.
1441 * Removes tags, octets, entities, and if strict is enabled, will only keep
1442 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1443 * raw username (the username in the parameter), and the value of $strict as
1444 * parameters for the 'sanitize_user' filter.
1448 * @param string $username The username to be sanitized.
1449 * @param bool $strict If set limits $username to specific characters. Default false.
1450 * @return string The sanitized username, after passing through filters.
1452 function sanitize_user( $username, $strict = false ) {
1453 $raw_username = $username;
1454 $username = wp_strip_all_tags( $username );
1455 $username = remove_accents( $username );
1457 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1458 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1460 // If strict, reduce to ASCII for max portability.
1462 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1464 $username = trim( $username );
1465 // Consolidate contiguous whitespace
1466 $username = preg_replace( '|\s+|', ' ', $username );
1469 * Filter a sanitized username string.
1473 * @param string $username Sanitized username.
1474 * @param string $raw_username The username prior to sanitization.
1475 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1477 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1481 * Sanitizes a string key.
1483 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1487 * @param string $key String key
1488 * @return string Sanitized key
1490 function sanitize_key( $key ) {
1492 $key = strtolower( $key );
1493 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1496 * Filter a sanitized key string.
1500 * @param string $key Sanitized key.
1501 * @param string $raw_key The key prior to sanitization.
1503 return apply_filters( 'sanitize_key', $key, $raw_key );
1507 * Sanitizes a title, or returns a fallback title.
1509 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1510 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1515 * @param string $title The string to be sanitized.
1516 * @param string $fallback_title Optional. A title to use if $title is empty.
1517 * @param string $context Optional. The operation for which the string is sanitized
1518 * @return string The sanitized string.
1520 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1521 $raw_title = $title;
1523 if ( 'save' == $context )
1524 $title = remove_accents($title);
1527 * Filter a sanitized title string.
1531 * @param string $title Sanitized title.
1532 * @param string $raw_title The title prior to sanitization.
1533 * @param string $context The context for which the title is being sanitized.
1535 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1537 if ( '' === $title || false === $title )
1538 $title = $fallback_title;
1544 * Sanitizes a title with the 'query' context.
1546 * Used for querying the database for a value from URL.
1550 * @param string $title The string to be sanitized.
1551 * @return string The sanitized string.
1553 function sanitize_title_for_query( $title ) {
1554 return sanitize_title( $title, '', 'query' );
1558 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1560 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1561 * Whitespace becomes a dash.
1565 * @param string $title The title to be sanitized.
1566 * @param string $raw_title Optional. Not used.
1567 * @param string $context Optional. The operation for which the string is sanitized.
1568 * @return string The sanitized title.
1570 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1571 $title = strip_tags($title);
1572 // Preserve escaped octets.
1573 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1574 // Remove percent signs that are not part of an octet.
1575 $title = str_replace('%', '', $title);
1577 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1579 if (seems_utf8($title)) {
1580 if (function_exists('mb_strtolower')) {
1581 $title = mb_strtolower($title, 'UTF-8');
1583 $title = utf8_uri_encode($title, 200);
1586 $title = strtolower($title);
1588 if ( 'save' == $context ) {
1589 // Convert nbsp, ndash and mdash to hyphens
1590 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1591 // Convert nbsp, ndash and mdash HTML entities to hyphens
1592 $title = str_replace( array( ' ', ' ', '–', '–', '—', '—' ), '-', $title );
1594 // Strip these characters entirely
1595 $title = str_replace( array(
1599 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1601 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1602 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1603 // copy, reg, deg, hellip and trade
1604 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1606 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1607 // grave accent, macron, caron
1608 '%cc%80', '%cc%84', '%cc%8c',
1611 // Convert times to x
1612 $title = str_replace( '%c3%97', 'x', $title );
1615 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1616 $title = str_replace('.', '-', $title);
1618 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1619 $title = preg_replace('/\s+/', '-', $title);
1620 $title = preg_replace('|-+|', '-', $title);
1621 $title = trim($title, '-');
1627 * Ensures a string is a valid SQL 'order by' clause.
1629 * Accepts one or more columns, with or without a sort order (ASC / DESC).
1630 * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
1632 * Also accepts 'RAND()'.
1636 * @param string $orderby Order by clause to be validated.
1637 * @return string|false Returns $orderby if valid, false otherwise.
1639 function sanitize_sql_orderby( $orderby ) {
1640 if ( preg_match( '/^\s*(([a-z0-9_]+|`[a-z0-9_]+`)(\s+(ASC|DESC))?\s*(,\s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^\s*RAND\(\s*\)\s*$/i', $orderby ) ) {
1647 * Sanitizes an HTML classname to ensure it only contains valid characters.
1649 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1650 * string then it will return the alternative value supplied.
1652 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1656 * @param string $class The classname to be sanitized
1657 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1658 * Defaults to an empty string.
1659 * @return string The sanitized value
1661 function sanitize_html_class( $class, $fallback = '' ) {
1662 //Strip out any % encoded octets
1663 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1665 //Limit to A-Z,a-z,0-9,_,-
1666 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1668 if ( '' == $sanitized && $fallback ) {
1669 return sanitize_html_class( $fallback );
1672 * Filter a sanitized HTML class string.
1676 * @param string $sanitized The sanitized HTML class.
1677 * @param string $class HTML class before sanitization.
1678 * @param string $fallback The fallback string.
1680 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1684 * Converts lone & characters into `&` (a.k.a. `&`)
1688 * @param string $content String of characters to be converted.
1689 * @param string $deprecated Not used.
1690 * @return string Converted string.
1692 function convert_chars( $content, $deprecated = '' ) {
1693 if ( ! empty( $deprecated ) ) {
1694 _deprecated_argument( __FUNCTION__, '0.71' );
1697 if ( strpos( $content, '&' ) !== false ) {
1698 $content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content );
1705 * Converts invalid Unicode references range to valid range.
1709 * @param string $content String with entities that need converting.
1710 * @return string Converted string.
1712 function convert_invalid_entities( $content ) {
1713 $wp_htmltranswinuni = array(
1714 '€' => '€', // the Euro sign
1716 '‚' => '‚', // these are Windows CP1252 specific characters
1717 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1718 '„' => '„',
1719 '…' => '…',
1720 '†' => '†',
1721 '‡' => '‡',
1722 'ˆ' => 'ˆ',
1723 '‰' => '‰',
1724 'Š' => 'Š',
1725 '‹' => '‹',
1726 'Œ' => 'Œ',
1728 'Ž' => 'Ž',
1731 '‘' => '‘',
1732 '’' => '’',
1733 '“' => '“',
1734 '”' => '”',
1735 '•' => '•',
1736 '–' => '–',
1737 '—' => '—',
1738 '˜' => '˜',
1739 '™' => '™',
1740 'š' => 'š',
1741 '›' => '›',
1742 'œ' => 'œ',
1744 'ž' => 'ž',
1745 'Ÿ' => 'Ÿ'
1748 if ( strpos( $content, '' ) !== false ) {
1749 $content = strtr( $content, $wp_htmltranswinuni );
1756 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1760 * @param string $text Text to be balanced
1761 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1762 * @return string Balanced text
1764 function balanceTags( $text, $force = false ) {
1765 if ( $force || get_option('use_balanceTags') == 1 ) {
1766 return force_balance_tags( $text );
1773 * Balances tags of string using a modified stack.
1777 * @author Leonard Lin <leonard@acm.org>
1779 * @copyright November 4, 2001
1781 * @todo Make better - change loop condition to $text in 1.2
1782 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1783 * 1.1 Fixed handling of append/stack pop order of end text
1784 * Added Cleaning Hooks
1787 * @param string $text Text to be balanced.
1788 * @return string Balanced text.
1790 function force_balance_tags( $text ) {
1791 $tagstack = array();
1795 // Known single-entity/self-closing tags
1796 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1797 // Tags that can be immediately nested within themselves
1798 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1800 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1801 $text = str_replace('< !--', '< !--', $text);
1802 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1803 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1805 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1806 $newtext .= $tagqueue;
1808 $i = strpos($text, $regex[0]);
1809 $l = strlen($regex[0]);
1811 // clear the shifter
1814 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1815 $tag = strtolower(substr($regex[1],1));
1816 // if too many closing tags
1817 if ( $stacksize <= 0 ) {
1819 // or close to be safe $tag = '/' . $tag;
1821 // if stacktop value = tag close value then pop
1822 elseif ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1823 $tag = '</' . $tag . '>'; // Close Tag
1825 array_pop( $tagstack );
1827 } else { // closing tag not at top, search for it
1828 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1829 if ( $tagstack[$j] == $tag ) {
1830 // add tag to tagqueue
1831 for ( $k = $stacksize-1; $k >= $j; $k--) {
1832 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1840 } else { // Begin Tag
1841 $tag = strtolower($regex[1]);
1845 // If it's an empty tag "< >", do nothing
1849 // ElseIf it presents itself as a self-closing tag...
1850 elseif ( substr( $regex[2], -1 ) == '/' ) {
1851 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1852 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1853 if ( ! in_array( $tag, $single_tags ) )
1854 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1856 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1857 elseif ( in_array($tag, $single_tags) ) {
1860 // Else it's not a single-entity tag
1862 // If the top of the stack is the same as the tag we want to push, close previous tag
1863 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1864 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1867 $stacksize = array_push( $tagstack, $tag );
1871 $attributes = $regex[2];
1872 if ( ! empty( $attributes ) && $attributes[0] != '>' )
1873 $attributes = ' ' . $attributes;
1875 $tag = '<' . $tag . $attributes . '>';
1876 //If already queuing a close tag, then put this tag on, too
1877 if ( !empty($tagqueue) ) {
1882 $newtext .= substr($text, 0, $i) . $tag;
1883 $text = substr($text, $i + $l);
1887 $newtext .= $tagqueue;
1889 // Add Remaining text
1893 while( $x = array_pop($tagstack) )
1894 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1896 // WP fix for the bug with HTML comments
1897 $newtext = str_replace("< !--","<!--",$newtext);
1898 $newtext = str_replace("< !--","< !--",$newtext);
1904 * Acts on text which is about to be edited.
1906 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1907 * to convert special characters to HTML entities. If $richedit is set to true,
1908 * it is simply a holder for the 'format_to_edit' filter.
1911 * @since 4.4.0 The `$richedit` parameter was renamed to `$rich_text` for clarity.
1913 * @param string $content The text about to be edited.
1914 * @param bool $rich_text Optional. Whether `$content` should be considered rich text,
1915 * in which case it would not be passed through esc_textarea().
1917 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1919 function format_to_edit( $content, $rich_text = false ) {
1921 * Filter the text to be formatted for editing.
1925 * @param string $content The text, prior to formatting for editing.
1927 $content = apply_filters( 'format_to_edit', $content );
1929 $content = esc_textarea( $content );
1934 * Add leading zeros when necessary.
1936 * If you set the threshold to '4' and the number is '10', then you will get
1937 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1938 * will get back '5000'.
1940 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1941 * and the size of the number. If the number is large enough, then no zeros will
1946 * @param int $number Number to append zeros to if not greater than threshold.
1947 * @param int $threshold Digit places number needs to be to not have zeros added.
1948 * @return string Adds leading zeros to number if needed.
1950 function zeroise( $number, $threshold ) {
1951 return sprintf( '%0' . $threshold . 's', $number );
1955 * Adds backslashes before letters and before a number at the start of a string.
1959 * @param string $string Value to which backslashes will be added.
1960 * @return string String with backslashes inserted.
1962 function backslashit( $string ) {
1963 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1964 $string = '\\\\' . $string;
1965 return addcslashes( $string, 'A..Za..z' );
1969 * Appends a trailing slash.
1971 * Will remove trailing forward and backslashes if it exists already before adding
1972 * a trailing forward slash. This prevents double slashing a string or path.
1974 * The primary use of this is for paths and thus should be used for paths. It is
1975 * not restricted to paths and offers no specific path support.
1979 * @param string $string What to add the trailing slash to.
1980 * @return string String with trailing slash added.
1982 function trailingslashit( $string ) {
1983 return untrailingslashit( $string ) . '/';
1987 * Removes trailing forward slashes and backslashes if they exist.
1989 * The primary use of this is for paths and thus should be used for paths. It is
1990 * not restricted to paths and offers no specific path support.
1994 * @param string $string What to remove the trailing slashes from.
1995 * @return string String without the trailing slashes.
1997 function untrailingslashit( $string ) {
1998 return rtrim( $string, '/\\' );
2002 * Adds slashes to escape strings.
2004 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
2005 * http://www.php.net/magic_quotes} for more details.
2009 * @param string $gpc The string returned from HTTP request data.
2010 * @return string Returns a string escaped with slashes.
2012 function addslashes_gpc($gpc) {
2013 if ( get_magic_quotes_gpc() )
2014 $gpc = stripslashes($gpc);
2016 return wp_slash($gpc);
2020 * Navigates through an array, object, or scalar, and removes slashes from the values.
2024 * @param mixed $value The value to be stripped.
2025 * @return mixed Stripped value.
2027 function stripslashes_deep( $value ) {
2028 return map_deep( $value, 'stripslashes_from_strings_only' );
2032 * Callback function for `stripslashes_deep()` which strips slashes from strings.
2036 * @param mixed $value The array or string to be stripped.
2037 * @return mixed $value The stripped value.
2039 function stripslashes_from_strings_only( $value ) {
2040 return is_string( $value ) ? stripslashes( $value ) : $value;
2044 * Navigates through an array, object, or scalar, and encodes the values to be used in a URL.
2048 * @param mixed $value The array or string to be encoded.
2049 * @return mixed $value The encoded value.
2051 function urlencode_deep( $value ) {
2052 return map_deep( $value, 'urlencode' );
2056 * Navigates through an array, object, or scalar, and raw-encodes the values to be used in a URL.
2060 * @param mixed $value The array or string to be encoded.
2061 * @return mixed $value The encoded value.
2063 function rawurlencode_deep( $value ) {
2064 return map_deep( $value, 'rawurlencode' );
2068 * Navigates through an array, object, or scalar, and decodes URL-encoded values
2072 * @param mixed $value The array or string to be decoded.
2073 * @return mixed $value The decoded value.
2075 function urldecode_deep( $value ) {
2076 return map_deep( $value, 'urldecode' );
2080 * Converts email addresses characters to HTML entities to block spam bots.
2084 * @param string $email_address Email address.
2085 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
2086 * @return string Converted email address.
2088 function antispambot( $email_address, $hex_encoding = 0 ) {
2089 $email_no_spam_address = '';
2090 for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
2091 $j = rand( 0, 1 + $hex_encoding );
2093 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
2094 } elseif ( $j == 1 ) {
2095 $email_no_spam_address .= $email_address[$i];
2096 } elseif ( $j == 2 ) {
2097 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
2101 return str_replace( '@', '@', $email_no_spam_address );
2105 * Callback to convert URI match to HTML A element.
2107 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2108 * make_clickable()}.
2113 * @param array $matches Single Regex Match.
2114 * @return string HTML A element with URI address.
2116 function _make_url_clickable_cb( $matches ) {
2119 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
2120 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
2121 // Then we can let the parenthesis balancer do its thing below.
2122 $url .= $matches[3];
2125 $suffix = $matches[3];
2128 // Include parentheses in the URL only if paired
2129 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
2130 $suffix = strrchr( $url, ')' ) . $suffix;
2131 $url = substr( $url, 0, strrpos( $url, ')' ) );
2134 $url = esc_url($url);
2138 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
2142 * Callback to convert URL match to HTML A element.
2144 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2145 * make_clickable()}.
2150 * @param array $matches Single Regex Match.
2151 * @return string HTML A element with URL address.
2153 function _make_web_ftp_clickable_cb( $matches ) {
2155 $dest = $matches[2];
2156 $dest = 'http://' . $dest;
2158 // removed trailing [.,;:)] from URL
2159 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
2160 $ret = substr($dest, -1);
2161 $dest = substr($dest, 0, strlen($dest)-1);
2164 $dest = esc_url($dest);
2168 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
2172 * Callback to convert email address match to HTML A element.
2174 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2175 * make_clickable()}.
2180 * @param array $matches Single Regex Match.
2181 * @return string HTML A element with email address.
2183 function _make_email_clickable_cb( $matches ) {
2184 $email = $matches[2] . '@' . $matches[3];
2185 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
2189 * Convert plaintext URI to HTML links.
2191 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
2196 * @param string $text Content to convert URIs.
2197 * @return string Content with converted URIs.
2199 function make_clickable( $text ) {
2201 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
2202 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
2203 foreach ( $textarr as $piece ) {
2205 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) || preg_match( '|^<script[\s>]|i', $piece ) || preg_match( '|^<style[\s>]|i', $piece ) )
2207 elseif ( $nested_code_pre && ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) || '</script>' === strtolower( $piece ) || '</style>' === strtolower( $piece ) ) )
2210 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
2215 // Long strings might contain expensive edge cases ...
2216 if ( 10000 < strlen( $piece ) ) {
2218 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
2219 if ( 2101 < strlen( $chunk ) ) {
2220 $r .= $chunk; // Too big, no whitespace: bail.
2222 $r .= make_clickable( $chunk );
2226 $ret = " $piece "; // Pad with whitespace to simplify the regexes
2229 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
2231 [\\w]{1,20}+:// # Scheme and hier-part prefix
2232 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
2233 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
2234 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
2235 [\'.,;:!?)] # Punctuation URL character
2236 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
2239 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
2240 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
2241 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
2243 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
2245 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
2246 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
2248 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
2253 // Cleanup of accidental links within links
2254 return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
2258 * Breaks a string into chunks by splitting at whitespace characters.
2259 * The length of each returned chunk is as close to the specified length goal as possible,
2260 * with the caveat that each chunk includes its trailing delimiter.
2261 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
2263 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
2265 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
2267 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
2269 * 0 => '1234 67890 ', // 11 characters: Perfect split
2270 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
2271 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
2272 * 3 => '1234 890 ', // 11 characters: Perfect split
2273 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
2274 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
2275 * 6 => ' 45678 ', // 11 characters: Perfect split
2276 * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
2282 * @param string $string The string to split.
2283 * @param int $goal The desired chunk length.
2284 * @return array Numeric array of chunks.
2286 function _split_str_by_whitespace( $string, $goal ) {
2289 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
2291 while ( $goal < strlen( $string_nullspace ) ) {
2292 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
2294 if ( false === $pos ) {
2295 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
2296 if ( false === $pos ) {
2301 $chunks[] = substr( $string, 0, $pos + 1 );
2302 $string = substr( $string, $pos + 1 );
2303 $string_nullspace = substr( $string_nullspace, $pos + 1 );
2307 $chunks[] = $string;
2314 * Adds rel nofollow string to all HTML A elements in content.
2318 * @param string $text Content that may contain HTML A elements.
2319 * @return string Converted content.
2321 function wp_rel_nofollow( $text ) {
2322 // This is a pre save filter, so text is already escaped.
2323 $text = stripslashes($text);
2324 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
2325 return wp_slash( $text );
2329 * Callback to add rel=nofollow string to HTML A element.
2331 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2332 * string to prevent from invalidating (X)HTML.
2336 * @param array $matches Single Match
2337 * @return string HTML A Element with rel nofollow.
2339 function wp_rel_nofollow_callback( $matches ) {
2340 $text = $matches[1];
2341 $atts = shortcode_parse_atts( $matches[1] );
2344 if ( preg_match( '%href=["\'](' . preg_quote( set_url_scheme( home_url(), 'http' ) ) . ')%i', $text ) ||
2345 preg_match( '%href=["\'](' . preg_quote( set_url_scheme( home_url(), 'https' ) ) . ')%i', $text )
2350 if ( ! empty( $atts['rel'] ) ) {
2351 $parts = array_map( 'trim', explode( ' ', $atts['rel'] ) );
2352 if ( false === array_search( 'nofollow', $parts ) ) {
2353 $parts[] = 'nofollow';
2355 $rel = implode( ' ', $parts );
2356 unset( $atts['rel'] );
2359 foreach ( $atts as $name => $value ) {
2360 $html .= "{$name}=\"$value\" ";
2362 $text = trim( $html );
2364 return "<a $text rel=\"$rel\">";
2368 * Convert one smiley code to the icon graphic file equivalent.
2370 * Callback handler for {@link convert_smilies()}.
2371 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2372 * `<img>` string for that smiley.
2376 * @global array $wpsmiliestrans
2378 * @param array $matches Single match. Smiley code to convert to image.
2379 * @return string Image string for smiley.
2381 function translate_smiley( $matches ) {
2382 global $wpsmiliestrans;
2384 if ( count( $matches ) == 0 )
2387 $smiley = trim( reset( $matches ) );
2388 $img = $wpsmiliestrans[ $smiley ];
2391 $ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
2392 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
2394 // Don't convert smilies that aren't images - they're probably emoji.
2395 if ( ! in_array( $ext, $image_exts ) ) {
2400 * Filter the Smiley image URL before it's used in the image element.
2404 * @param string $smiley_url URL for the smiley image.
2405 * @param string $img Filename for the smiley image.
2406 * @param string $site_url Site URL, as returned by site_url().
2408 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2410 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
2414 * Convert text equivalent of smilies to images.
2416 * Will only convert smilies if the option 'use_smilies' is true and the global
2417 * used in the function isn't empty.
2421 * @global string|array $wp_smiliessearch
2423 * @param string $text Content to convert smilies from text.
2424 * @return string Converted content with text smilies replaced with images.
2426 function convert_smilies( $text ) {
2427 global $wp_smiliessearch;
2429 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2430 // HTML loop taken from texturize function, could possible be consolidated
2431 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2432 $stop = count( $textarr );// loop stuff
2434 // Ignore proessing of specific tags
2435 $tags_to_ignore = 'code|pre|style|script|textarea';
2436 $ignore_block_element = '';
2438 for ( $i = 0; $i < $stop; $i++ ) {
2439 $content = $textarr[$i];
2441 // If we're in an ignore block, wait until we find its closing tag
2442 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2443 $ignore_block_element = $matches[1];
2446 // If it's not a tag and not in ignore block
2447 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2448 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2451 // did we exit ignore block
2452 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2453 $ignore_block_element = '';
2456 $output .= $content;
2459 // return default text.
2466 * Verifies that an email is valid.
2468 * Does not grok i18n domains. Not RFC compliant.
2472 * @param string $email Email address to verify.
2473 * @param bool $deprecated Deprecated.
2474 * @return string|bool Either false or the valid email address.
2476 function is_email( $email, $deprecated = false ) {
2477 if ( ! empty( $deprecated ) )
2478 _deprecated_argument( __FUNCTION__, '3.0' );
2480 // Test for the minimum length the email can be
2481 if ( strlen( $email ) < 3 ) {
2483 * Filter whether an email address is valid.
2485 * This filter is evaluated under several different contexts, such as 'email_too_short',
2486 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2487 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2491 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2492 * @param string $email The email address being checked.
2493 * @param string $context Context under which the email was tested.
2495 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2498 // Test for an @ character after the first position
2499 if ( strpos( $email, '@', 1 ) === false ) {
2500 /** This filter is documented in wp-includes/formatting.php */
2501 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2504 // Split out the local and domain parts
2505 list( $local, $domain ) = explode( '@', $email, 2 );
2508 // Test for invalid characters
2509 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2510 /** This filter is documented in wp-includes/formatting.php */
2511 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2515 // Test for sequences of periods
2516 if ( preg_match( '/\.{2,}/', $domain ) ) {
2517 /** This filter is documented in wp-includes/formatting.php */
2518 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2521 // Test for leading and trailing periods and whitespace
2522 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2523 /** This filter is documented in wp-includes/formatting.php */
2524 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2527 // Split the domain into subs
2528 $subs = explode( '.', $domain );
2530 // Assume the domain will have at least two subs
2531 if ( 2 > count( $subs ) ) {
2532 /** This filter is documented in wp-includes/formatting.php */
2533 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2536 // Loop through each sub
2537 foreach ( $subs as $sub ) {
2538 // Test for leading and trailing hyphens and whitespace
2539 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2540 /** This filter is documented in wp-includes/formatting.php */
2541 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2544 // Test for invalid characters
2545 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2546 /** This filter is documented in wp-includes/formatting.php */
2547 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2551 // Congratulations your email made it!
2552 /** This filter is documented in wp-includes/formatting.php */
2553 return apply_filters( 'is_email', $email, $email, null );
2557 * Convert to ASCII from email subjects.
2561 * @param string $string Subject line
2562 * @return string Converted string to ASCII
2564 function wp_iso_descrambler( $string ) {
2565 /* this may only work with iso-8859-1, I'm afraid */
2566 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2569 $subject = str_replace('_', ' ', $matches[2]);
2570 return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
2575 * Helper function to convert hex encoded chars to ASCII
2580 * @param array $match The preg_replace_callback matches array
2581 * @return string Converted chars
2583 function _wp_iso_convert( $match ) {
2584 return chr( hexdec( strtolower( $match[1] ) ) );
2588 * Returns a date in the GMT equivalent.
2590 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2591 * timezone_string available, the date is assumed to be in that timezone,
2592 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2593 * format can be overridden using the $format parameter.
2597 * @param string $string The date to be converted.
2598 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2599 * @return string GMT version of the date provided.
2601 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2602 $tz = get_option( 'timezone_string' );
2604 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2605 if ( ! $datetime ) {
2606 return gmdate( $format, 0 );
2608 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2609 $string_gmt = $datetime->format( $format );
2611 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 ) ) {
2612 $datetime = strtotime( $string );
2613 if ( false === $datetime ) {
2614 return gmdate( $format, 0 );
2616 return gmdate( $format, $datetime );
2618 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2619 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2625 * Converts a GMT date into the correct format for the blog.
2627 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2628 * timezone_string available, the returned date is in that timezone, otherwise
2629 * it simply adds the value of gmt_offset. Return format can be overridden
2630 * using the $format parameter
2634 * @param string $string The date to be converted.
2635 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2636 * @return string Formatted date relative to the timezone / GMT offset.
2638 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2639 $tz = get_option( 'timezone_string' );
2641 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2643 return date( $format, 0 );
2644 $datetime->setTimezone( new DateTimeZone( $tz ) );
2645 $string_localtime = $datetime->format( $format );
2647 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) )
2648 return date( $format, 0 );
2649 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2650 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2652 return $string_localtime;
2656 * Computes an offset in seconds from an iso8601 timezone.
2660 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2661 * @return int|float The offset in seconds.
2663 function iso8601_timezone_to_offset( $timezone ) {
2664 // $timezone is either 'Z' or '[+|-]hhmm'
2665 if ($timezone == 'Z') {
2668 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2669 $hours = intval(substr($timezone, 1, 2));
2670 $minutes = intval(substr($timezone, 3, 4)) / 60;
2671 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2677 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2681 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2682 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2683 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2685 function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
2686 $timezone = strtolower($timezone);
2688 if ($timezone == 'gmt') {
2690 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);
2692 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2693 $offset = iso8601_timezone_to_offset($date_bits[7]);
2694 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2695 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2698 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2699 $timestamp -= $offset;
2701 return gmdate('Y-m-d H:i:s', $timestamp);
2703 } elseif ($timezone == 'user') {
2704 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);
2709 * Strips out all characters that are not allowable in an email.
2713 * @param string $email Email address to filter.
2714 * @return string Filtered email address.
2716 function sanitize_email( $email ) {
2717 // Test for the minimum length the email can be
2718 if ( strlen( $email ) < 3 ) {
2720 * Filter a sanitized email address.
2722 * This filter is evaluated under several contexts, including 'email_too_short',
2723 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2724 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2728 * @param string $email The sanitized email address.
2729 * @param string $email The email address, as provided to sanitize_email().
2730 * @param string $message A message to pass to the user.
2732 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2735 // Test for an @ character after the first position
2736 if ( strpos( $email, '@', 1 ) === false ) {
2737 /** This filter is documented in wp-includes/formatting.php */
2738 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2741 // Split out the local and domain parts
2742 list( $local, $domain ) = explode( '@', $email, 2 );
2745 // Test for invalid characters
2746 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2747 if ( '' === $local ) {
2748 /** This filter is documented in wp-includes/formatting.php */
2749 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2753 // Test for sequences of periods
2754 $domain = preg_replace( '/\.{2,}/', '', $domain );
2755 if ( '' === $domain ) {
2756 /** This filter is documented in wp-includes/formatting.php */
2757 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2760 // Test for leading and trailing periods and whitespace
2761 $domain = trim( $domain, " \t\n\r\0\x0B." );
2762 if ( '' === $domain ) {
2763 /** This filter is documented in wp-includes/formatting.php */
2764 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2767 // Split the domain into subs
2768 $subs = explode( '.', $domain );
2770 // Assume the domain will have at least two subs
2771 if ( 2 > count( $subs ) ) {
2772 /** This filter is documented in wp-includes/formatting.php */
2773 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2776 // Create an array that will contain valid subs
2777 $new_subs = array();
2779 // Loop through each sub
2780 foreach ( $subs as $sub ) {
2781 // Test for leading and trailing hyphens
2782 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2784 // Test for invalid characters
2785 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2787 // If there's anything left, add it to the valid subs
2788 if ( '' !== $sub ) {
2793 // If there aren't 2 or more valid subs
2794 if ( 2 > count( $new_subs ) ) {
2795 /** This filter is documented in wp-includes/formatting.php */
2796 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2799 // Join valid subs into the new domain
2800 $domain = join( '.', $new_subs );
2802 // Put the email back together
2803 $email = $local . '@' . $domain;
2805 // Congratulations your email made it!
2806 /** This filter is documented in wp-includes/formatting.php */
2807 return apply_filters( 'sanitize_email', $email, $email, null );
2811 * Determines the difference between two timestamps.
2813 * The difference is returned in a human readable format such as "1 hour",
2814 * "5 mins", "2 days".
2818 * @param int $from Unix timestamp from which the difference begins.
2819 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2820 * @return string Human readable time difference.
2822 function human_time_diff( $from, $to = '' ) {
2823 if ( empty( $to ) ) {
2827 $diff = (int) abs( $to - $from );
2829 if ( $diff < HOUR_IN_SECONDS ) {
2830 $mins = round( $diff / MINUTE_IN_SECONDS );
2833 /* translators: min=minute */
2834 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2835 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2836 $hours = round( $diff / HOUR_IN_SECONDS );
2839 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2840 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2841 $days = round( $diff / DAY_IN_SECONDS );
2844 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2845 } elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2846 $weeks = round( $diff / WEEK_IN_SECONDS );
2849 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2850 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
2851 $months = round( $diff / MONTH_IN_SECONDS );
2854 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2855 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2856 $years = round( $diff / YEAR_IN_SECONDS );
2859 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2863 * Filter the human readable difference between two timestamps.
2867 * @param string $since The difference in human readable text.
2868 * @param int $diff The difference in seconds.
2869 * @param int $from Unix timestamp from which the difference begins.
2870 * @param int $to Unix timestamp to end the time difference.
2872 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2876 * Generates an excerpt from the content, if needed.
2878 * The excerpt word amount will be 55 words and if the amount is greater than
2879 * that, then the string ' […]' will be appended to the excerpt. If the string
2880 * is less than 55 words, then the content will be returned as is.
2882 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2883 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2887 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2888 * @return string The excerpt.
2890 function wp_trim_excerpt( $text = '' ) {
2891 $raw_excerpt = $text;
2892 if ( '' == $text ) {
2893 $text = get_the_content('');
2895 $text = strip_shortcodes( $text );
2897 /** This filter is documented in wp-includes/post-template.php */
2898 $text = apply_filters( 'the_content', $text );
2899 $text = str_replace(']]>', ']]>', $text);
2902 * Filter the number of words in an excerpt.
2906 * @param int $number The number of words. Default 55.
2908 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2910 * Filter the string in the "more" link displayed after a trimmed excerpt.
2914 * @param string $more_string The string shown within the more link.
2916 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2917 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2920 * Filter the trimmed excerpt string.
2924 * @param string $text The trimmed text.
2925 * @param string $raw_excerpt The text prior to trimming.
2927 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2931 * Trims text to a certain number of words.
2933 * This function is localized. For languages that count 'words' by the individual
2934 * character (such as East Asian languages), the $num_words argument will apply
2935 * to the number of individual characters.
2939 * @param string $text Text to trim.
2940 * @param int $num_words Number of words. Default 55.
2941 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2942 * @return string Trimmed text.
2944 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2945 if ( null === $more ) {
2946 $more = __( '…' );
2949 $original_text = $text;
2950 $text = wp_strip_all_tags( $text );
2953 * translators: If your word count is based on single characters (e.g. East Asian characters),
2954 * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
2955 * Do not translate into your own language.
2957 if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2958 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2959 preg_match_all( '/./u', $text, $words_array );
2960 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2963 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2967 if ( count( $words_array ) > $num_words ) {
2968 array_pop( $words_array );
2969 $text = implode( $sep, $words_array );
2970 $text = $text . $more;
2972 $text = implode( $sep, $words_array );
2976 * Filter the text content after words have been trimmed.
2980 * @param string $text The trimmed text.
2981 * @param int $num_words The number of words to trim the text to. Default 5.
2982 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2983 * @param string $original_text The text before it was trimmed.
2985 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2989 * Converts named entities into numbered entities.
2993 * @param string $text The text within which entities will be converted.
2994 * @return string Text with converted entities.
2996 function ent2ncr( $text ) {
2999 * Filter text before named entities are converted into numbered entities.
3001 * A non-null string must be returned for the filter to be evaluated.
3005 * @param null $converted_text The text to be converted. Default null.
3006 * @param string $text The text prior to entity conversion.
3008 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
3009 if ( null !== $filtered )
3013 '"' => '"',
3018 ' ' => ' ',
3019 '¡' => '¡',
3020 '¢' => '¢',
3021 '£' => '£',
3022 '¤' => '¤',
3023 '¥' => '¥',
3024 '¦' => '¦',
3025 '&brkbar;' => '¦',
3026 '§' => '§',
3027 '¨' => '¨',
3028 '¨' => '¨',
3029 '©' => '©',
3030 'ª' => 'ª',
3031 '«' => '«',
3032 '¬' => '¬',
3033 '­' => '­',
3034 '®' => '®',
3035 '¯' => '¯',
3036 '&hibar;' => '¯',
3037 '°' => '°',
3038 '±' => '±',
3039 '²' => '²',
3040 '³' => '³',
3041 '´' => '´',
3042 'µ' => 'µ',
3043 '¶' => '¶',
3044 '·' => '·',
3045 '¸' => '¸',
3046 '¹' => '¹',
3047 'º' => 'º',
3048 '»' => '»',
3049 '¼' => '¼',
3050 '½' => '½',
3051 '¾' => '¾',
3052 '¿' => '¿',
3053 'À' => 'À',
3054 'Á' => 'Á',
3055 'Â' => 'Â',
3056 'Ã' => 'Ã',
3057 'Ä' => 'Ä',
3058 'Å' => 'Å',
3059 'Æ' => 'Æ',
3060 'Ç' => 'Ç',
3061 'È' => 'È',
3062 'É' => 'É',
3063 'Ê' => 'Ê',
3064 'Ë' => 'Ë',
3065 'Ì' => 'Ì',
3066 'Í' => 'Í',
3067 'Î' => 'Î',
3068 'Ï' => 'Ï',
3069 'Ð' => 'Ð',
3070 'Ñ' => 'Ñ',
3071 'Ò' => 'Ò',
3072 'Ó' => 'Ó',
3073 'Ô' => 'Ô',
3074 'Õ' => 'Õ',
3075 'Ö' => 'Ö',
3076 '×' => '×',
3077 'Ø' => 'Ø',
3078 'Ù' => 'Ù',
3079 'Ú' => 'Ú',
3080 'Û' => 'Û',
3081 'Ü' => 'Ü',
3082 'Ý' => 'Ý',
3083 'Þ' => 'Þ',
3084 'ß' => 'ß',
3085 'à' => 'à',
3086 'á' => 'á',
3087 'â' => 'â',
3088 'ã' => 'ã',
3089 'ä' => 'ä',
3090 'å' => 'å',
3091 'æ' => 'æ',
3092 'ç' => 'ç',
3093 'è' => 'è',
3094 'é' => 'é',
3095 'ê' => 'ê',
3096 'ë' => 'ë',
3097 'ì' => 'ì',
3098 'í' => 'í',
3099 'î' => 'î',
3100 'ï' => 'ï',
3101 'ð' => 'ð',
3102 'ñ' => 'ñ',
3103 'ò' => 'ò',
3104 'ó' => 'ó',
3105 'ô' => 'ô',
3106 'õ' => 'õ',
3107 'ö' => 'ö',
3108 '÷' => '÷',
3109 'ø' => 'ø',
3110 'ù' => 'ù',
3111 'ú' => 'ú',
3112 'û' => 'û',
3113 'ü' => 'ü',
3114 'ý' => 'ý',
3115 'þ' => 'þ',
3116 'ÿ' => 'ÿ',
3117 'Œ' => 'Œ',
3118 'œ' => 'œ',
3119 'Š' => 'Š',
3120 'š' => 'š',
3121 'Ÿ' => 'Ÿ',
3122 'ƒ' => 'ƒ',
3123 'ˆ' => 'ˆ',
3124 '˜' => '˜',
3125 'Α' => 'Α',
3126 'Β' => 'Β',
3127 'Γ' => 'Γ',
3128 'Δ' => 'Δ',
3129 'Ε' => 'Ε',
3130 'Ζ' => 'Ζ',
3131 'Η' => 'Η',
3132 'Θ' => 'Θ',
3133 'Ι' => 'Ι',
3134 'Κ' => 'Κ',
3135 'Λ' => 'Λ',
3139 'Ο' => 'Ο',
3141 'Ρ' => 'Ρ',
3142 'Σ' => 'Σ',
3143 'Τ' => 'Τ',
3144 'Υ' => 'Υ',
3145 'Φ' => 'Φ',
3146 'Χ' => 'Χ',
3147 'Ψ' => 'Ψ',
3148 'Ω' => 'Ω',
3149 'α' => 'α',
3150 'β' => 'β',
3151 'γ' => 'γ',
3152 'δ' => 'δ',
3153 'ε' => 'ε',
3154 'ζ' => 'ζ',
3155 'η' => 'η',
3156 'θ' => 'θ',
3157 'ι' => 'ι',
3158 'κ' => 'κ',
3159 'λ' => 'λ',
3163 'ο' => 'ο',
3165 'ρ' => 'ρ',
3166 'ς' => 'ς',
3167 'σ' => 'σ',
3168 'τ' => 'τ',
3169 'υ' => 'υ',
3170 'φ' => 'φ',
3171 'χ' => 'χ',
3172 'ψ' => 'ψ',
3173 'ω' => 'ω',
3174 'ϑ' => 'ϑ',
3175 'ϒ' => 'ϒ',
3176 'ϖ' => 'ϖ',
3177 ' ' => ' ',
3178 ' ' => ' ',
3179 ' ' => ' ',
3180 '‌' => '‌',
3181 '‍' => '‍',
3182 '‎' => '‎',
3183 '‏' => '‏',
3184 '–' => '–',
3185 '—' => '—',
3186 '‘' => '‘',
3187 '’' => '’',
3188 '‚' => '‚',
3189 '“' => '“',
3190 '”' => '”',
3191 '„' => '„',
3192 '†' => '†',
3193 '‡' => '‡',
3194 '•' => '•',
3195 '…' => '…',
3196 '‰' => '‰',
3197 '′' => '′',
3198 '″' => '″',
3199 '‹' => '‹',
3200 '›' => '›',
3201 '‾' => '‾',
3202 '⁄' => '⁄',
3203 '€' => '€',
3204 'ℑ' => 'ℑ',
3205 '℘' => '℘',
3206 'ℜ' => 'ℜ',
3207 '™' => '™',
3208 'ℵ' => 'ℵ',
3209 '↵' => '↵',
3210 '⇐' => '⇐',
3211 '⇑' => '⇑',
3212 '⇒' => '⇒',
3213 '⇓' => '⇓',
3214 '⇔' => '⇔',
3215 '∀' => '∀',
3216 '∂' => '∂',
3217 '∃' => '∃',
3218 '∅' => '∅',
3219 '∇' => '∇',
3220 '∈' => '∈',
3221 '∉' => '∉',
3222 '∋' => '∋',
3223 '∏' => '∏',
3224 '∑' => '∑',
3225 '−' => '−',
3226 '∗' => '∗',
3227 '√' => '√',
3228 '∝' => '∝',
3229 '∞' => '∞',
3230 '∠' => '∠',
3231 '∧' => '∧',
3232 '∨' => '∨',
3233 '∩' => '∩',
3234 '∪' => '∪',
3235 '∫' => '∫',
3236 '∴' => '∴',
3237 '∼' => '∼',
3238 '≅' => '≅',
3239 '≈' => '≈',
3240 '≠' => '≠',
3241 '≡' => '≡',
3242 '≤' => '≤',
3243 '≥' => '≥',
3244 '⊂' => '⊂',
3245 '⊃' => '⊃',
3246 '⊄' => '⊄',
3247 '⊆' => '⊆',
3248 '⊇' => '⊇',
3249 '⊕' => '⊕',
3250 '⊗' => '⊗',
3251 '⊥' => '⊥',
3252 '⋅' => '⋅',
3253 '⌈' => '⌈',
3254 '⌉' => '⌉',
3255 '⌊' => '⌊',
3256 '⌋' => '⌋',
3257 '⟨' => '〈',
3258 '⟩' => '〉',
3259 '←' => '←',
3260 '↑' => '↑',
3261 '→' => '→',
3262 '↓' => '↓',
3263 '↔' => '↔',
3264 '◊' => '◊',
3265 '♠' => '♠',
3266 '♣' => '♣',
3267 '♥' => '♥',
3268 '♦' => '♦'
3271 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
3275 * Formats text for the editor.
3277 * Generally the browsers treat everything inside a textarea as text, but
3278 * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
3280 * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
3281 * filter will be applied to an empty string.
3285 * @see _WP_Editors::editor()
3287 * @param string $text The text to be formatted.
3288 * @param string $default_editor The default editor for the current user.
3289 * It is usually either 'html' or 'tinymce'.
3290 * @return string The formatted text after filter is applied.
3292 function format_for_editor( $text, $default_editor = null ) {
3294 $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
3298 * Filter the text after it is formatted for the editor.
3302 * @param string $text The formatted text.
3303 * @param string $default_editor The default editor for the current user.
3304 * It is usually either 'html' or 'tinymce'.
3306 return apply_filters( 'format_for_editor', $text, $default_editor );
3310 * Perform a deep string replace operation to ensure the values in $search are no longer present
3312 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
3313 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
3314 * str_replace would return
3319 * @param string|array $search The value being searched for, otherwise known as the needle.
3320 * An array may be used to designate multiple needles.
3321 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
3322 * @return string The string with the replaced svalues.
3324 function _deep_replace( $search, $subject ) {
3325 $subject = (string) $subject;
3329 $subject = str_replace( $search, '', $subject, $count );
3336 * Escapes data for use in a MySQL query.
3338 * Usually you should prepare queries using wpdb::prepare().
3339 * Sometimes, spot-escaping is required or useful. One example
3340 * is preparing an array for use in an IN clause.
3344 * @global wpdb $wpdb WordPress database abstraction object.
3346 * @param string|array $data Unescaped data
3347 * @return string|array Escaped data
3349 function esc_sql( $data ) {
3351 return $wpdb->_escape( $data );
3355 * Checks and cleans a URL.
3357 * A number of characters are removed from the URL. If the URL is for displaying
3358 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3359 * is applied to the returned cleaned URL.
3363 * @param string $url The URL to be cleaned.
3364 * @param array $protocols Optional. An array of acceptable protocols.
3365 * Defaults to return value of wp_allowed_protocols()
3366 * @param string $_context Private. Use esc_url_raw() for database usage.
3367 * @return string The cleaned $url after the 'clean_url' filter is applied.
3369 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3370 $original_url = $url;
3375 $url = str_replace( ' ', '%20', $url );
3376 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url);
3378 if ( '' === $url ) {
3382 if ( 0 !== stripos( $url, 'mailto:' ) ) {
3383 $strip = array('%0d', '%0a', '%0D', '%0A');
3384 $url = _deep_replace($strip, $url);
3387 $url = str_replace(';//', '://', $url);
3388 /* If the URL doesn't appear to contain a scheme, we
3389 * presume it needs http:// prepended (unless a relative
3390 * link starting with /, # or ? or a php file).
3392 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3393 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3394 $url = 'http://' . $url;
3396 // Replace ampersands and single quotes only when displaying.
3397 if ( 'display' == $_context ) {
3398 $url = wp_kses_normalize_entities( $url );
3399 $url = str_replace( '&', '&', $url );
3400 $url = str_replace( "'", ''', $url );
3403 if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
3405 $parsed = wp_parse_url( $url );
3408 if ( isset( $parsed['scheme'] ) ) {
3409 $front .= $parsed['scheme'] . '://';
3410 } elseif ( '/' === $url[0] ) {
3414 if ( isset( $parsed['user'] ) ) {
3415 $front .= $parsed['user'];
3418 if ( isset( $parsed['pass'] ) ) {
3419 $front .= ':' . $parsed['pass'];
3422 if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
3426 if ( isset( $parsed['host'] ) ) {
3427 $front .= $parsed['host'];
3430 if ( isset( $parsed['port'] ) ) {
3431 $front .= ':' . $parsed['port'];
3434 $end_dirty = str_replace( $front, '', $url );
3435 $end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
3436 $url = str_replace( $end_dirty, $end_clean, $url );
3440 if ( '/' === $url[0] ) {
3441 $good_protocol_url = $url;
3443 if ( ! is_array( $protocols ) )
3444 $protocols = wp_allowed_protocols();
3445 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3446 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3451 * Filter a string cleaned and escaped for output as a URL.
3455 * @param string $good_protocol_url The cleaned URL to be returned.
3456 * @param string $original_url The URL prior to cleaning.
3457 * @param string $_context If 'display', replace ampersands and single quotes only.
3459 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3463 * Performs esc_url() for database usage.
3467 * @param string $url The URL to be cleaned.
3468 * @param array $protocols An array of acceptable protocols.
3469 * @return string The cleaned URL.
3471 function esc_url_raw( $url, $protocols = null ) {
3472 return esc_url( $url, $protocols, 'db' );
3476 * Convert entities, while preserving already-encoded entities.
3478 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3482 * @param string $myHTML The text to be converted.
3483 * @return string Converted text.
3485 function htmlentities2( $myHTML ) {
3486 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3487 $translation_table[chr(38)] = '&';
3488 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3492 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3494 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3495 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3496 * be in single quotes. The filter 'js_escape' is also applied here.
3500 * @param string $text The text to be escaped.
3501 * @return string Escaped text.
3503 function esc_js( $text ) {
3504 $safe_text = wp_check_invalid_utf8( $text );
3505 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3506 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3507 $safe_text = str_replace( "\r", '', $safe_text );
3508 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3510 * Filter a string cleaned and escaped for output in JavaScript.
3512 * Text passed to esc_js() is stripped of invalid or special characters,
3513 * and properly slashed for output.
3517 * @param string $safe_text The text after it has been escaped.
3518 * @param string $text The text prior to being escaped.
3520 return apply_filters( 'js_escape', $safe_text, $text );
3524 * Escaping for HTML blocks.
3528 * @param string $text
3531 function esc_html( $text ) {
3532 $safe_text = wp_check_invalid_utf8( $text );
3533 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3535 * Filter a string cleaned and escaped for output in HTML.
3537 * Text passed to esc_html() is stripped of invalid or special characters
3542 * @param string $safe_text The text after it has been escaped.
3543 * @param string $text The text prior to being escaped.
3545 return apply_filters( 'esc_html', $safe_text, $text );
3549 * Escaping for HTML attributes.
3553 * @param string $text
3556 function esc_attr( $text ) {
3557 $safe_text = wp_check_invalid_utf8( $text );
3558 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3560 * Filter a string cleaned and escaped for output in an HTML attribute.
3562 * Text passed to esc_attr() is stripped of invalid or special characters
3567 * @param string $safe_text The text after it has been escaped.
3568 * @param string $text The text prior to being escaped.
3570 return apply_filters( 'attribute_escape', $safe_text, $text );
3574 * Escaping for textarea values.
3578 * @param string $text
3581 function esc_textarea( $text ) {
3582 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3584 * Filter a string cleaned and escaped for output in a textarea element.
3588 * @param string $safe_text The text after it has been escaped.
3589 * @param string $text The text prior to being escaped.
3591 return apply_filters( 'esc_textarea', $safe_text, $text );
3595 * Escape an HTML tag name.
3599 * @param string $tag_name
3602 function tag_escape( $tag_name ) {
3603 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3605 * Filter a string cleaned and escaped for output as an HTML tag.
3609 * @param string $safe_tag The tag name after it has been escaped.
3610 * @param string $tag_name The text before it was escaped.
3612 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3616 * Convert full URL paths to absolute paths.
3618 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3619 * beginning, so it isn't a true relative link, but from the web root base.
3622 * @since 4.1.0 Support was added for relative URLs.
3624 * @param string $link Full URL path.
3625 * @return string Absolute path.
3627 function wp_make_link_relative( $link ) {
3628 return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
3632 * Sanitises various option values based on the nature of the option.
3634 * This is basically a switch statement which will pass $value through a number
3635 * of functions depending on the $option.
3639 * @global wpdb $wpdb WordPress database abstraction object.
3641 * @param string $option The name of the option.
3642 * @param string $value The unsanitised value.
3643 * @return string Sanitized value.
3645 function sanitize_option( $option, $value ) {
3648 $original_value = $value;
3651 switch ( $option ) {
3652 case 'admin_email' :
3653 case 'new_admin_email' :
3654 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3655 if ( is_wp_error( $value ) ) {
3656 $error = $value->get_error_message();
3658 $value = sanitize_email( $value );
3659 if ( ! is_email( $value ) ) {
3660 $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
3665 case 'thumbnail_size_w':
3666 case 'thumbnail_size_h':
3667 case 'medium_size_w':
3668 case 'medium_size_h':
3669 case 'medium_large_size_w':
3670 case 'medium_large_size_h':
3671 case 'large_size_w':
3672 case 'large_size_h':
3673 case 'mailserver_port':
3674 case 'comment_max_links':
3675 case 'page_on_front':
3676 case 'page_for_posts':
3677 case 'rss_excerpt_length':
3678 case 'default_category':
3679 case 'default_email_category':
3680 case 'default_link_category':
3681 case 'close_comments_days_old':
3682 case 'comments_per_page':
3683 case 'thread_comments_depth':
3684 case 'users_can_register':
3685 case 'start_of_week':
3687 $value = absint( $value );
3690 case 'posts_per_page':
3691 case 'posts_per_rss':
3692 $value = (int) $value;
3693 if ( empty($value) )
3696 $value = abs($value);
3699 case 'default_ping_status':
3700 case 'default_comment_status':
3701 // Options that if not there have 0 value but need to be something like "closed"
3702 if ( $value == '0' || $value == '')
3706 case 'blogdescription':
3708 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3709 if ( is_wp_error( $value ) ) {
3710 $error = $value->get_error_message();
3712 $value = esc_html( $value );
3716 case 'blog_charset':
3717 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3721 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3722 if ( null === $value )
3725 $value = intval( $value );
3730 case 'mailserver_url':
3731 case 'mailserver_login':
3732 case 'mailserver_pass':
3734 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3735 if ( is_wp_error( $value ) ) {
3736 $error = $value->get_error_message();
3738 $value = strip_tags( $value );
3739 $value = wp_kses_data( $value );
3744 $value = explode( "\n", $value );
3745 $value = array_filter( array_map( 'trim', $value ) );
3746 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3747 $value = implode( "\n", $value );
3751 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3755 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3756 if ( is_wp_error( $value ) ) {
3757 $error = $value->get_error_message();
3759 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3760 $value = esc_url_raw( $value );
3762 $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3768 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3769 if ( is_wp_error( $value ) ) {
3770 $error = $value->get_error_message();
3772 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3773 $value = esc_url_raw( $value );
3775 $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3781 $allowed = get_available_languages();
3782 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3783 $allowed[] = WPLANG;
3785 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3786 $value = get_option( $option );
3790 case 'illegal_names':
3791 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3792 if ( is_wp_error( $value ) ) {
3793 $error = $value->get_error_message();
3795 if ( ! is_array( $value ) )
3796 $value = explode( ' ', $value );
3798 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3805 case 'limited_email_domains':
3806 case 'banned_email_domains':
3807 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3808 if ( is_wp_error( $value ) ) {
3809 $error = $value->get_error_message();
3811 if ( ! is_array( $value ) )
3812 $value = explode( "\n", $value );
3814 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3817 foreach ( $domains as $domain ) {
3818 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
3827 case 'timezone_string':
3828 $allowed_zones = timezone_identifiers_list();
3829 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3830 $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
3834 case 'permalink_structure':
3835 case 'category_base':
3837 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3838 if ( is_wp_error( $value ) ) {
3839 $error = $value->get_error_message();
3841 $value = esc_url_raw( $value );
3842 $value = str_replace( 'http://', '', $value );
3846 case 'default_role' :
3847 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3848 $value = 'subscriber';
3851 case 'moderation_keys':
3852 case 'blacklist_keys':
3853 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3854 if ( is_wp_error( $value ) ) {
3855 $error = $value->get_error_message();
3857 $value = explode( "\n", $value );
3858 $value = array_filter( array_map( 'trim', $value ) );
3859 $value = array_unique( $value );
3860 $value = implode( "\n", $value );
3865 if ( ! empty( $error ) ) {
3866 $value = get_option( $option );
3867 if ( function_exists( 'add_settings_error' ) ) {
3868 add_settings_error( $option, "invalid_{$option}", $error );
3873 * Filter an option value following sanitization.
3876 * @since 4.3.0 Added the `$original_value` parameter.
3878 * @param string $value The sanitized option value.
3879 * @param string $option The option name.
3880 * @param string $original_value The original value passed to the function.
3882 return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
3886 * Maps a function to all non-iterable elements of an array or an object.
3888 * This is similar to `array_walk_recursive()` but acts upon objects too.
3892 * @param mixed $value The array, object, or scalar.
3893 * @param callable $callback The function to map onto $value.
3894 * @return mixed The value with the callback applied to all non-arrays and non-objects inside it.
3896 function map_deep( $value, $callback ) {
3897 if ( is_array( $value ) ) {
3898 foreach ( $value as $index => $item ) {
3899 $value[ $index ] = map_deep( $item, $callback );
3901 } elseif ( is_object( $value ) ) {
3902 $object_vars = get_object_vars( $value );
3903 foreach ( $object_vars as $property_name => $property_value ) {
3904 $value->$property_name = map_deep( $property_value, $callback );
3907 $value = call_user_func( $callback, $value );
3914 * Parses a string into variables to be stored in an array.
3916 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3917 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3921 * @param string $string The string to be parsed.
3922 * @param array $array Variables will be stored in this array.
3924 function wp_parse_str( $string, &$array ) {
3925 parse_str( $string, $array );
3926 if ( get_magic_quotes_gpc() )
3927 $array = stripslashes_deep( $array );
3929 * Filter the array of variables derived from a parsed string.
3933 * @param array $array The array populated with variables.
3935 $array = apply_filters( 'wp_parse_str', $array );
3939 * Convert lone less than signs.
3941 * KSES already converts lone greater than signs.
3945 * @param string $text Text to be converted.
3946 * @return string Converted text.
3948 function wp_pre_kses_less_than( $text ) {
3949 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3953 * Callback function used by preg_replace.
3957 * @param array $matches Populated by matches to preg_replace.
3958 * @return string The text returned after esc_html if needed.
3960 function wp_pre_kses_less_than_callback( $matches ) {
3961 if ( false === strpos($matches[0], '>') )
3962 return esc_html($matches[0]);
3967 * WordPress implementation of PHP sprintf() with filters.
3970 * @link http://www.php.net/sprintf
3972 * @param string $pattern The string which formatted args are inserted.
3973 * @param mixed $args ,... Arguments to be formatted into the $pattern string.
3974 * @return string The formatted string.
3976 function wp_sprintf( $pattern ) {
3977 $args = func_get_args();
3978 $len = strlen($pattern);
3982 while ( $len > $start ) {
3983 // Last character: append and break
3984 if ( strlen($pattern) - 1 == $start ) {
3985 $result .= substr($pattern, -1);
3989 // Literal %: append and continue
3990 if ( substr($pattern, $start, 2) == '%%' ) {
3996 // Get fragment before next %
3997 $end = strpos($pattern, '%', $start + 1);
3998 if ( false === $end )
4000 $fragment = substr($pattern, $start, $end - $start);
4002 // Fragment has a specifier
4003 if ( $pattern[$start] == '%' ) {
4004 // Find numbered arguments or take the next one in order
4005 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
4006 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
4007 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
4010 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
4014 * Filter a fragment from the pattern passed to wp_sprintf().
4016 * If the fragment is unchanged, then sprintf() will be run on the fragment.
4020 * @param string $fragment A fragment from the pattern.
4021 * @param string $arg The argument.
4023 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
4024 if ( $_fragment != $fragment )
4025 $fragment = $_fragment;
4027 $fragment = sprintf($fragment, strval($arg) );
4030 // Append to result and move to next fragment
4031 $result .= $fragment;
4038 * Localize list items before the rest of the content.
4040 * The '%l' must be at the first characters can then contain the rest of the
4041 * content. The list items will have ', ', ', and', and ' and ' added depending
4042 * on the amount of list items in the $args parameter.
4046 * @param string $pattern Content containing '%l' at the beginning.
4047 * @param array $args List items to prepend to the content and replace '%l'.
4048 * @return string Localized list items and rest of the content.
4050 function wp_sprintf_l( $pattern, $args ) {
4052 if ( substr($pattern, 0, 2) != '%l' )
4055 // Nothing to work with
4060 * Filter the translated delimiters used by wp_sprintf_l().
4061 * Placeholders (%s) are included to assist translators and then
4062 * removed before the array of strings reaches the filter.
4064 * Please note: Ampersands and entities should be avoided here.
4068 * @param array $delimiters An array of translated delimiters.
4070 $l = apply_filters( 'wp_sprintf_l', array(
4071 /* translators: used to join items in a list with more than 2 items */
4072 'between' => sprintf( __('%s, %s'), '', '' ),
4073 /* translators: used to join last two items in a list with more than 2 times */
4074 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
4075 /* translators: used to join items in a list with only 2 items */
4076 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
4079 $args = (array) $args;
4080 $result = array_shift($args);
4081 if ( count($args) == 1 )
4082 $result .= $l['between_only_two'] . array_shift($args);
4083 // Loop when more than two args
4086 $arg = array_shift($args);
4089 $result .= $l['between_last_two'] . $arg;
4091 $result .= $l['between'] . $arg;
4093 return $result . substr($pattern, 2);
4097 * Safely extracts not more than the first $count characters from html string.
4099 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
4100 * be counted as one character. For example & will be counted as 4, < as
4105 * @param string $str String to get the excerpt from.
4106 * @param int $count Maximum number of characters to take.
4107 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
4108 * @return string The excerpt.
4110 function wp_html_excerpt( $str, $count, $more = null ) {
4111 if ( null === $more )
4113 $str = wp_strip_all_tags( $str, true );
4114 $excerpt = mb_substr( $str, 0, $count );
4115 // remove part of an entity at the end
4116 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
4117 if ( $str != $excerpt )
4118 $excerpt = trim( $excerpt ) . $more;
4123 * Add a Base url to relative links in passed content.
4125 * By default it supports the 'src' and 'href' attributes. However this can be
4126 * changed via the 3rd param.
4130 * @global string $_links_add_base
4132 * @param string $content String to search for links in.
4133 * @param string $base The base URL to prefix to links.
4134 * @param array $attrs The attributes which should be processed.
4135 * @return string The processed content.
4137 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
4138 global $_links_add_base;
4139 $_links_add_base = $base;
4140 $attrs = implode('|', (array)$attrs);
4141 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
4145 * Callback to add a base url to relative links in passed content.
4150 * @global string $_links_add_base
4152 * @param string $m The matched link.
4153 * @return string The processed link.
4155 function _links_add_base( $m ) {
4156 global $_links_add_base;
4157 //1 = attribute name 2 = quotation mark 3 = URL
4158 return $m[1] . '=' . $m[2] .
4159 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
4161 WP_Http::make_absolute_url( $m[3], $_links_add_base )
4167 * Adds a Target attribute to all links in passed content.
4169 * This function by default only applies to `<a>` tags, however this can be
4170 * modified by the 3rd param.
4172 * *NOTE:* Any current target attributed will be stripped and replaced.
4176 * @global string $_links_add_target
4178 * @param string $content String to search for links in.
4179 * @param string $target The Target to add to the links.
4180 * @param array $tags An array of tags to apply to.
4181 * @return string The processed content.
4183 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
4184 global $_links_add_target;
4185 $_links_add_target = $target;
4186 $tags = implode('|', (array)$tags);
4187 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
4191 * Callback to add a target attribute to all links in passed content.
4196 * @global string $_links_add_target
4198 * @param string $m The matched link.
4199 * @return string The processed link.
4201 function _links_add_target( $m ) {
4202 global $_links_add_target;
4204 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
4205 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
4209 * Normalize EOL characters and strip duplicate whitespace.
4213 * @param string $str The string to normalize.
4214 * @return string The normalized string.
4216 function normalize_whitespace( $str ) {
4217 $str = trim( $str );
4218 $str = str_replace( "\r", "\n", $str );
4219 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
4224 * Properly strip all HTML tags including script and style
4226 * This differs from strip_tags() because it removes the contents of
4227 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
4228 * will return 'something'. wp_strip_all_tags will return ''
4232 * @param string $string String containing HTML tags
4233 * @param bool $remove_breaks Optional. Whether to remove left over line breaks and white space chars
4234 * @return string The processed string.
4236 function wp_strip_all_tags($string, $remove_breaks = false) {
4237 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
4238 $string = strip_tags($string);
4240 if ( $remove_breaks )
4241 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
4243 return trim( $string );
4247 * Sanitize a string from user input or from the db
4249 * check for invalid UTF-8,
4250 * Convert single < characters to entity,
4252 * remove line breaks, tabs and extra white space,
4257 * @param string $str
4260 function sanitize_text_field( $str ) {
4261 $filtered = wp_check_invalid_utf8( $str );
4263 if ( strpos($filtered, '<') !== false ) {
4264 $filtered = wp_pre_kses_less_than( $filtered );
4265 // This will strip extra whitespace for us.
4266 $filtered = wp_strip_all_tags( $filtered, true );
4268 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
4272 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
4273 $filtered = str_replace($match[0], '', $filtered);
4278 // Strip out the whitespace that may now exist after removing the octets.
4279 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
4283 * Filter a sanitized text field string.
4287 * @param string $filtered The sanitized string.
4288 * @param string $str The string prior to being sanitized.
4290 return apply_filters( 'sanitize_text_field', $filtered, $str );
4294 * i18n friendly version of basename()
4298 * @param string $path A path.
4299 * @param string $suffix If the filename ends in suffix this will also be cut off.
4302 function wp_basename( $path, $suffix = '' ) {
4303 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
4307 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
4309 * Violating our coding standards for a good function name.
4313 * @staticvar string|false $dblq
4315 * @param string $text The text to be modified.
4316 * @return string The modified text.
4318 function capital_P_dangit( $text ) {
4319 // Simple replacement for titles
4320 $current_filter = current_filter();
4321 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
4322 return str_replace( 'Wordpress', 'WordPress', $text );
4323 // Still here? Use the more judicious replacement
4324 static $dblq = false;
4325 if ( false === $dblq ) {
4326 $dblq = _x( '“', 'opening curly double quote' );
4329 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
4330 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
4335 * Sanitize a mime type
4339 * @param string $mime_type Mime type
4340 * @return string Sanitized mime type
4342 function sanitize_mime_type( $mime_type ) {
4343 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
4345 * Filter a mime type following sanitization.
4349 * @param string $sani_mime_type The sanitized mime type.
4350 * @param string $mime_type The mime type prior to sanitization.
4352 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
4356 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
4360 * @param string $to_ping Space or carriage return separated URLs
4361 * @return string URLs starting with the http or https protocol, separated by a carriage return.
4363 function sanitize_trackback_urls( $to_ping ) {
4364 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
4365 foreach ( $urls_to_ping as $k => $url ) {
4366 if ( !preg_match( '#^https?://.#i', $url ) )
4367 unset( $urls_to_ping[$k] );
4369 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
4370 $urls_to_ping = implode( "\n", $urls_to_ping );
4372 * Filter a list of trackback URLs following sanitization.
4374 * The string returned here consists of a space or carriage return-delimited list
4375 * of trackback URLs.
4379 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
4380 * @param string $to_ping Space or carriage return separated URLs before sanitization.
4382 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
4386 * Add slashes to a string or array of strings.
4388 * This should be used when preparing data for core API that expects slashed data.
4389 * This should not be used to escape data going directly into an SQL query.
4393 * @param string|array $value String or array of strings to slash.
4394 * @return string|array Slashed $value
4396 function wp_slash( $value ) {
4397 if ( is_array( $value ) ) {
4398 foreach ( $value as $k => $v ) {
4399 if ( is_array( $v ) ) {
4400 $value[$k] = wp_slash( $v );
4402 $value[$k] = addslashes( $v );
4406 $value = addslashes( $value );
4413 * Remove slashes from a string or array of strings.
4415 * This should be used to remove slashes from data passed to core API that
4416 * expects data to be unslashed.
4420 * @param string|array $value String or array of strings to unslash.
4421 * @return string|array Unslashed $value
4423 function wp_unslash( $value ) {
4424 return stripslashes_deep( $value );
4428 * Extract and return the first URL from passed content.
4432 * @param string $content A string which might contain a URL.
4433 * @return string|false The found URL.
4435 function get_url_in_content( $content ) {
4436 if ( empty( $content ) ) {
4440 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
4441 return esc_url_raw( $matches[2] );
4448 * Returns the regexp for common whitespace characters.
4450 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
4451 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
4452 * sequence was found to be unreliable due to random inclusion of the A0 byte.
4456 * @staticvar string $spaces
4458 * @return string The spaces regexp.
4460 function wp_spaces_regexp() {
4461 static $spaces = '';
4463 if ( empty( $spaces ) ) {
4465 * Filter the regexp for common whitespace characters.
4467 * This string is substituted for the \s sequence as needed in regular
4468 * expressions. For websites not written in English, different characters
4469 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
4470 * sequence may not be in use.
4474 * @param string $spaces Regexp pattern for matching common whitespace characters.
4476 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );
4483 * Print the important emoji-related styles.
4487 * @staticvar bool $printed
4489 function print_emoji_styles() {
4490 static $printed = false;
4498 <style type="text/css">
4501 display: inline !important;
4502 border: none !important;
4503 box-shadow: none !important;
4504 height: 1em !important;
4505 width: 1em !important;
4506 margin: 0 .07em !important;
4507 vertical-align: -0.1em !important;
4508 background: none !important;
4509 padding: 0 !important;
4517 * @global string $wp_version
4518 * @staticvar bool $printed
4520 function print_emoji_detection_script() {
4522 static $printed = false;
4532 * Filter the URL where emoji images are hosted.
4536 * @param string The emoji base URL.
4538 'baseUrl' => apply_filters( 'emoji_url', 'https://s.w.org/images/core/emoji/72x72/' ),
4541 * Filter the extension of the emoji files.
4545 * @param string The emoji extension. Default .png.
4547 'ext' => apply_filters( 'emoji_ext', '.png' ),
4550 $version = 'ver=' . $wp_version;
4552 if ( SCRIPT_DEBUG ) {
4553 $settings['source'] = array(
4554 /** This filter is documented in wp-includes/class.wp-scripts.php */
4555 'wpemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji.js?$version" ), 'wpemoji' ),
4556 /** This filter is documented in wp-includes/class.wp-scripts.php */
4557 'twemoji' => apply_filters( 'script_loader_src', includes_url( "js/twemoji.js?$version" ), 'twemoji' ),
4561 <script type="text/javascript">
4562 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4563 <?php readfile( ABSPATH . WPINC . "/js/wp-emoji-loader.js" ); ?>
4567 $settings['source'] = array(
4568 /** This filter is documented in wp-includes/class.wp-scripts.php */
4569 'concatemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji-release.min.js?$version" ), 'concatemoji' ),
4573 * If you're looking at a src version of this file, you'll see an "include"
4574 * statement below. This is used by the `grunt build` process to directly
4575 * include a minified version of wp-emoji-loader.js, instead of using the
4576 * readfile() method from above.
4578 * If you're looking at a build version of this file, you'll see a string of
4579 * minified JavaScript. If you need to debug it, please turn on SCRIPT_DEBUG
4580 * and edit wp-emoji-loader.js directly.
4583 <script type="text/javascript">
4584 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4585 !function(a,b,c){function d(a){var c,d,e,f=b.createElement("canvas"),g=f.getContext&&f.getContext("2d"),h=String.fromCharCode;if(!g||!g.fillText)return!1;switch(g.textBaseline="top",g.font="600 32px Arial",a){case"flag":return g.fillText(h(55356,56806,55356,56826),0,0),f.toDataURL().length>3e3;case"diversity":return g.fillText(h(55356,57221),0,0),c=g.getImageData(16,16,1,1).data,d=c[0]+","+c[1]+","+c[2]+","+c[3],g.fillText(h(55356,57221,55356,57343),0,0),c=g.getImageData(16,16,1,1).data,e=c[0]+","+c[1]+","+c[2]+","+c[3],d!==e;case"simple":return g.fillText(h(55357,56835),0,0),0!==g.getImageData(16,16,1,1).data[0];case"unicode8":return g.fillText(h(55356,57135),0,0),0!==g.getImageData(16,16,1,1).data[0]}return!1}function e(a){var c=b.createElement("script");c.src=a,c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g,h,i;for(i=Array("simple","flag","unicode8","diversity"),c.supports={everything:!0,everythingExceptFlag:!0},h=0;h<i.length;h++)c.supports[i[h]]=d(i[h]),c.supports.everything=c.supports.everything&&c.supports[i[h]],"flag"!==i[h]&&(c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&c.supports[i[h]]);c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&!c.supports.flag,c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.everything||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings);
4592 * Convert any 4 byte emoji in a string to their equivalent HTML entity.
4594 * Currently, only Unicode 7 emoji are supported. Skin tone modifiers are allowed,
4595 * all other Unicode 8 emoji will be added when the spec is finalised.
4597 * This allows us to store emoji in a DB using the utf8 character set.
4601 * @param string $content The content to encode.
4602 * @return string The encoded content.
4604 function wp_encode_emoji( $content ) {
4605 if ( function_exists( 'mb_convert_encoding' ) ) {
4607 \x23\xE2\x83\xA3 # Digits
4608 [\x30-\x39]\xE2\x83\xA3
4609 | \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
4610 | \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
4611 | \xF0\x9F\x98[\x80-\xBF] # Smilies
4612 | \xF0\x9F\x99[\x80-\x8F]
4613 | \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
4617 if ( preg_match_all( $regex, $content, $matches ) ) {
4618 if ( ! empty( $matches[1] ) ) {
4619 foreach ( $matches[1] as $emoji ) {
4621 * UTF-32's hex encoding is the same as HTML's hex encoding.
4622 * So, by converting the emoji from UTF-8 to UTF-32, we magically
4623 * get the correct hex encoding.
4625 $unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
4626 if ( isset( $unpacked[1] ) ) {
4627 $entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
4628 $content = str_replace( $emoji, $entity, $content );
4639 * Convert emoji to a static img element.
4643 * @param string $text The content to encode.
4644 * @return string The encoded content.
4646 function wp_staticize_emoji( $text ) {
4647 $text = wp_encode_emoji( $text );
4649 /** This filter is documented in wp-includes/formatting.php */
4650 $cdn_url = apply_filters( 'emoji_url', 'https://s.w.org/images/core/emoji/72x72/' );
4652 /** This filter is documented in wp-includes/formatting.php */
4653 $ext = apply_filters( 'emoji_ext', '.png' );
4657 * HTML loop taken from smiley function, which was taken from texturize function.
4658 * It'll never be consolidated.
4660 * First, capture the tags as well as in between.
4662 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
4663 $stop = count( $textarr );
4665 // Ignore processing of specific tags.
4666 $tags_to_ignore = 'code|pre|style|script|textarea';
4667 $ignore_block_element = '';
4669 for ( $i = 0; $i < $stop; $i++ ) {
4670 $content = $textarr[$i];
4672 // If we're in an ignore block, wait until we find its closing tag.
4673 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
4674 $ignore_block_element = $matches[1];
4677 // If it's not a tag and not in ignore block.
4678 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
4680 if ( preg_match_all( '/(DZ(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches ) ) {
4681 if ( ! empty( $matches[0] ) ) {
4682 foreach ( $matches[0] as $flag ) {
4683 $chars = str_replace( array( '&#x', ';'), '', $flag );
4685 list( $char1, $char2 ) = str_split( $chars, 5 );
4686 $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char1 . '-' . $char2 . $ext, html_entity_decode( $flag ) );
4688 $content = str_replace( $flag, $entity, $content );
4693 // Loosely match the Emoji Unicode range.
4694 $regex = '/(&#x[2-3][0-9a-f]{3};|[1-6][0-9a-f]{2};)/';
4697 if ( preg_match_all( $regex, $content, $matches ) ) {
4698 if ( ! empty( $matches[1] ) ) {
4699 foreach ( $matches[1] as $emoji ) {
4700 $char = str_replace( array( '&#x', ';'), '', $emoji );
4701 $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode( $emoji ) );
4703 $content = str_replace( $emoji, $entity, $content );
4709 // Did we exit ignore block.
4710 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
4711 $ignore_block_element = '';
4714 $output .= $content;
4721 * Convert emoji in emails into static images.
4725 * @param array $mail The email data array.
4726 * @return array The email data array, with emoji in the message staticized.
4728 function wp_staticize_emoji_for_email( $mail ) {
4729 if ( ! isset( $mail['message'] ) ) {
4734 * We can only transform the emoji into images if it's a text/html email.
4735 * To do that, here's a cut down version of the same process that happens
4736 * in wp_mail() - get the Content-Type from the headers, if there is one,
4737 * then pass it through the wp_mail_content_type filter, in case a plugin
4738 * is handling changing the Content-Type.
4741 if ( isset( $mail['headers'] ) ) {
4742 if ( is_array( $mail['headers'] ) ) {
4743 $headers = $mail['headers'];
4745 $headers = explode( "\n", str_replace( "\r\n", "\n", $mail['headers'] ) );
4749 foreach ( $headers as $header ) {
4750 if ( strpos($header, ':') === false ) {
4754 // Explode them out.
4755 list( $name, $content ) = explode( ':', trim( $header ), 2 );
4758 $name = trim( $name );
4759 $content = trim( $content );
4761 if ( 'content-type' === strtolower( $name ) ) {
4762 if ( strpos( $content, ';' ) !== false ) {
4763 list( $type, $charset ) = explode( ';', $content );
4764 $content_type = trim( $type );
4766 $content_type = trim( $content );
4772 // Set Content-Type if we don't have a content-type from the input headers.
4773 if ( ! isset( $content_type ) ) {
4774 $content_type = 'text/plain';
4777 /** This filter is documented in wp-includes/pluggable.php */
4778 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
4780 if ( 'text/html' === $content_type ) {
4781 $mail['message'] = wp_staticize_emoji( $mail['message'] );
4788 * Shorten a URL, to be used as link text.
4791 * @since 4.4.0 Moved to wp-includes/formatting.php from wp-admin/includes/misc.php and added $length param.
4793 * @param string $url URL to shorten.
4794 * @param int $length Optional. Maximum length of the shortened URL. Default 35 characters.
4795 * @return string Shortened URL.
4797 function url_shorten( $url, $length = 35 ) {
4798 $stripped = str_replace( array( 'https://', 'http://', 'www.' ), '', $url );
4799 $short_url = untrailingslashit( $stripped );
4801 if ( strlen( $short_url ) > $length ) {
4802 $short_url = substr( $short_url, 0, $length - 3 ) . '…';