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 $tagnames = array_keys( $shortcode_tags );
220 $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
221 $tagregexp = "(?:$tagregexp)(?![\\w-])"; // Excerpt of get_shortcode_regex().
224 '!' // Start of comment, after the <.
225 . '(?:' // Unroll the loop: Consume everything until --> is found.
226 . '-(?!->)' // Dash not followed by end of comment.
227 . '[^\-]*+' // Consume non-dashes.
228 . ')*+' // Loop possessively.
229 . '(?:-->)?'; // End of comment. If not found, match all input.
232 '\[' // Find start of shortcode.
233 . '[\/\[]?' // Shortcodes may begin with [/ or [[
234 . $tagregexp // Only match registered shortcodes, because performance.
236 . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
238 . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
239 . ')*+' // Possessive critical.
240 . '\]' // Find end of shortcode.
241 . '\]?'; // Shortcodes may end with ]]
244 '/(' // Capture the entire match.
245 . '<' // Find start of element.
246 . '(?(?=!--)' // Is this a comment?
247 . $comment_regex // Find end of comment.
249 . '[^>]*>' // Find end of element.
252 . $shortcode_regex // Find shortcodes.
255 $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
257 foreach ( $textarr as &$curl ) {
258 // Only call _wptexturize_pushpop_element if $curl is a delimiter.
260 if ( '<' === $first && '<!--' === substr( $curl, 0, 4 ) ) {
261 // This is an HTML comment delimeter.
265 } elseif ( '<' === $first && '>' === substr( $curl, -1 ) ) {
266 // This is an HTML element delimiter.
268 _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
270 } elseif ( '' === trim( $curl ) ) {
271 // This is a newline between delimiters. Performance improves when we check this.
275 } elseif ( '[' === $first && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
276 // This is a shortcode delimiter.
278 if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
279 // Looks like a normal shortcode.
280 _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
282 // Looks like an escaped shortcode.
286 } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
287 // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
289 $curl = str_replace( $static_characters, $static_replacements, $curl );
291 if ( false !== strpos( $curl, "'" ) ) {
292 $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
293 $curl = wptexturize_primes( $curl, "'", $prime, $open_sq_flag, $closing_single_quote );
294 $curl = str_replace( $apos_flag, $apos, $curl );
295 $curl = str_replace( $open_sq_flag, $opening_single_quote, $curl );
297 if ( false !== strpos( $curl, '"' ) ) {
298 $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
299 $curl = wptexturize_primes( $curl, '"', $double_prime, $open_q_flag, $closing_quote );
300 $curl = str_replace( $open_q_flag, $opening_quote, $curl );
302 if ( false !== strpos( $curl, '-' ) ) {
303 $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
306 // 9x9 (times), but never 0x9999
307 if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
308 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
309 $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1×$2', $curl );
313 $text = implode( '', $textarr );
315 // Replace each & with & unless it already looks like an entity.
316 return preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $text );
320 * Implements a logic tree to determine whether or not "7'." represents seven feet,
321 * then converts the special char into either a prime char or a closing quote char.
325 * @param string $haystack The plain text to be searched.
326 * @param string $needle The character to search for such as ' or ".
327 * @param string $prime The prime char to use for replacement.
328 * @param string $open_quote The opening quote char. Opening quote replacement must be
329 * accomplished already.
330 * @param string $close_quote The closing quote char to use for replacement.
331 * @return string The $haystack value after primes and quotes replacements.
333 function wptexturize_primes( $haystack, $needle, $prime, $open_quote, $close_quote ) {
334 $spaces = wp_spaces_regexp();
335 $flag = '<!--wp-prime-or-quote-->';
336 $quote_pattern = "/$needle(?=\\Z|[.,:;!?)}\\-\\]]|>|" . $spaces . ")/";
337 $prime_pattern = "/(?<=\\d)$needle/";
338 $flag_after_digit = "/(?<=\\d)$flag/";
339 $flag_no_digit = "/(?<!\\d)$flag/";
341 $sentences = explode( $open_quote, $haystack );
343 foreach( $sentences as $key => &$sentence ) {
344 if ( false === strpos( $sentence, $needle ) ) {
346 } elseif ( 0 !== $key && 0 === substr_count( $sentence, $close_quote ) ) {
347 $sentence = preg_replace( $quote_pattern, $flag, $sentence, -1, $count );
349 // This sentence appears to have multiple closing quotes. Attempt Vulcan logic.
350 $sentence = preg_replace( $flag_no_digit, $close_quote, $sentence, -1, $count2 );
351 if ( 0 === $count2 ) {
352 // Try looking for a quote followed by a period.
353 $count2 = substr_count( $sentence, "$flag." );
355 // Assume the rightmost quote-period match is the end of quotation.
356 $pos = strrpos( $sentence, "$flag." );
358 // When all else fails, make the rightmost candidate a closing quote.
359 // This is most likely to be problematic in the context of bug #18549.
360 $pos = strrpos( $sentence, $flag );
362 $sentence = substr_replace( $sentence, $close_quote, $pos, strlen( $flag ) );
364 // Use conventional replacement on any remaining primes and quotes.
365 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
366 $sentence = preg_replace( $flag_after_digit, $prime, $sentence );
367 $sentence = str_replace( $flag, $close_quote, $sentence );
368 } elseif ( 1 == $count ) {
369 // Found only one closing quote candidate, so give it priority over primes.
370 $sentence = str_replace( $flag, $close_quote, $sentence );
371 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
373 // No closing quotes found. Just run primes pattern.
374 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
377 $sentence = preg_replace( $prime_pattern, $prime, $sentence );
378 $sentence = preg_replace( $quote_pattern, $close_quote, $sentence );
380 if ( '"' == $needle && false !== strpos( $sentence, '"' ) ) {
381 $sentence = str_replace( '"', $close_quote, $sentence );
385 return implode( $open_quote, $sentences );
389 * Search for disabled element tags. Push element to stack on tag open and pop
392 * Assumes first char of $text is tag opening and last char is tag closing.
393 * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
398 * @param string $text Text to check. Must be a tag like `<html>` or `[shortcode]`.
399 * @param array $stack List of open tag elements.
400 * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
402 function _wptexturize_pushpop_element( $text, &$stack, $disabled_elements ) {
403 // Is it an opening tag or closing tag?
404 if ( '/' !== $text[1] ) {
407 } elseif ( 0 == count( $stack ) ) {
408 // Stack is empty. Just stop.
411 $opening_tag = false;
415 // Parse out the tag name.
416 $space = strpos( $text, ' ' );
417 if ( false === $space ) {
420 $space -= $name_offset;
422 $tag = substr( $text, $name_offset, $space );
424 // Handle disabled tags.
425 if ( in_array( $tag, $disabled_elements ) ) {
426 if ( $opening_tag ) {
428 * This disables texturize until we find a closing tag of our type
429 * (e.g. <pre>) even if there was invalid nesting before that
431 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
432 * "baba" won't be texturize
435 array_push( $stack, $tag );
436 } elseif ( end( $stack ) == $tag ) {
443 * Replaces double line-breaks with paragraph elements.
445 * A group of regex replaces used to identify text formatted with newlines and
446 * replace double line-breaks with HTML paragraph tags. The remaining line-breaks
447 * after conversion become <<br />> tags, unless $br is set to '0' or 'false'.
451 * @param string $pee The text which has to be formatted.
452 * @param bool $br Optional. If set, this will convert all remaining line-breaks
453 * after paragraphing. Default true.
454 * @return string Text which has been converted into correct paragraph tags.
456 function wpautop( $pee, $br = true ) {
459 if ( trim($pee) === '' )
462 // Just to make things a little easier, pad the end.
466 * Pre tags shouldn't be touched by autop.
467 * Replace pre tags with placeholders and bring them back after autop.
469 if ( strpos($pee, '<pre') !== false ) {
470 $pee_parts = explode( '</pre>', $pee );
471 $last_pee = array_pop($pee_parts);
475 foreach ( $pee_parts as $pee_part ) {
476 $start = strpos($pee_part, '<pre');
479 if ( $start === false ) {
484 $name = "<pre wp-pre-tag-$i></pre>";
485 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
487 $pee .= substr( $pee_part, 0, $start ) . $name;
493 // Change multiple <br>s into two line breaks, which will turn into paragraphs.
494 $pee = preg_replace('|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee);
496 $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)';
498 // Add a single line break above block-level opening tags.
499 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
501 // Add a double line break below block-level closing tags.
502 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
504 // Standardize newline characters to "\n".
505 $pee = str_replace(array("\r\n", "\r"), "\n", $pee);
507 // Find newlines in all elements and add placeholders.
508 $pee = wp_replace_in_html_tags( $pee, array( "\n" => " <!-- wpnl --> " ) );
510 // Collapse line breaks before and after <option> elements so they don't get autop'd.
511 if ( strpos( $pee, '<option' ) !== false ) {
512 $pee = preg_replace( '|\s*<option|', '<option', $pee );
513 $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
517 * Collapse line breaks inside <object> elements, before <param> and <embed> elements
518 * so they don't get autop'd.
520 if ( strpos( $pee, '</object>' ) !== false ) {
521 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
522 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
523 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
527 * Collapse line breaks inside <audio> and <video> elements,
528 * before and after <source> and <track> elements.
530 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
531 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
532 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
533 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
536 // Remove more than two contiguous line breaks.
537 $pee = preg_replace("/\n\n+/", "\n\n", $pee);
539 // Split up the contents into an array of strings, separated by double line breaks.
540 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
542 // Reset $pee prior to rebuilding.
545 // Rebuild the content as a string, wrapping every bit with a <p>.
546 foreach ( $pees as $tinkle ) {
547 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
550 // Under certain strange conditions it could create a P of entirely whitespace.
551 $pee = preg_replace('|<p>\s*</p>|', '', $pee);
553 // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
554 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
556 // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
557 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
559 // In some cases <li> may get wrapped in <p>, fix them.
560 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee);
562 // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
563 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
564 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
566 // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
567 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
569 // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
570 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
572 // Optionally insert line breaks.
574 // Replace newlines that shouldn't be touched with a placeholder.
575 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
578 $pee = str_replace( array( '<br>', '<br/>' ), '<br />', $pee );
580 // Replace any new line characters that aren't preceded by a <br /> with a <br />.
581 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee);
583 // Replace newline placeholders with newlines.
584 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
587 // If a <br /> tag is after an opening or closing block tag, remove it.
588 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
590 // If a <br /> tag is before a subset of opening or closing block tags, remove it.
591 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
592 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
594 // Replace placeholder <pre> tags with their original content.
595 if ( !empty($pre_tags) )
596 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
598 // Restore newlines in all elements.
599 if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
600 $pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
607 * Separate HTML elements and comments from the text.
611 * @param string $input The text which has to be formatted.
612 * @return array The formatted text.
614 function wp_html_split( $input ) {
617 if ( ! isset( $regex ) ) {
619 '!' // Start of comment, after the <.
620 . '(?:' // Unroll the loop: Consume everything until --> is found.
621 . '-(?!->)' // Dash not followed by end of comment.
622 . '[^\-]*+' // Consume non-dashes.
623 . ')*+' // Loop possessively.
624 . '(?:-->)?'; // End of comment. If not found, match all input.
627 '!\[CDATA\[' // Start of comment, after the <.
628 . '[^\]]*+' // Consume non-].
629 . '(?:' // Unroll the loop: Consume everything until ]]> is found.
630 . '](?!]>)' // One ] not followed by end of comment.
631 . '[^\]]*+' // Consume non-].
632 . ')*+' // Loop possessively.
633 . '(?:]]>)?'; // End of comment. If not found, match all input.
636 '/(' // Capture the entire match.
637 . '<' // Find start of element.
638 . '(?(?=!--)' // Is this a comment?
639 . $comments // Find end of comment.
641 . '(?(?=!\[CDATA\[)' // Is this a comment?
642 . $cdata // Find end of comment.
644 . '[^>]*>?' // Find end of element. If not found, match all input.
650 return preg_split( $regex, $input, -1, PREG_SPLIT_DELIM_CAPTURE );
654 * Replace characters or phrases within HTML elements only.
658 * @param string $haystack The text which has to be formatted.
659 * @param array $replace_pairs In the form array('from' => 'to', ...).
660 * @return string The formatted text.
662 function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
663 // Find all elements.
664 $textarr = wp_html_split( $haystack );
667 // Optimize when searching for one item.
668 if ( 1 === count( $replace_pairs ) ) {
669 // Extract $needle and $replace.
670 foreach ( $replace_pairs as $needle => $replace );
672 // Loop through delimeters (elements) only.
673 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
674 if ( false !== strpos( $textarr[$i], $needle ) ) {
675 $textarr[$i] = str_replace( $needle, $replace, $textarr[$i] );
680 // Extract all $needles.
681 $needles = array_keys( $replace_pairs );
683 // Loop through delimeters (elements) only.
684 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
685 foreach ( $needles as $needle ) {
686 if ( false !== strpos( $textarr[$i], $needle ) ) {
687 $textarr[$i] = strtr( $textarr[$i], $replace_pairs );
689 // After one strtr() break out of the foreach loop and look at next element.
697 $haystack = implode( $textarr );
704 * Newline preservation help function for wpautop
709 * @param array $matches preg_replace_callback matches array
712 function _autop_newline_preservation_helper( $matches ) {
713 return str_replace( "\n", "<WPPreserveNewline />", $matches[0] );
717 * Don't auto-p wrap shortcodes that stand alone
719 * Ensures that shortcodes are not wrapped in `<p>...</p>`.
723 * @global array $shortcode_tags
725 * @param string $pee The content.
726 * @return string The filtered content.
728 function shortcode_unautop( $pee ) {
729 global $shortcode_tags;
731 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
735 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
736 $spaces = wp_spaces_regexp();
740 . '<p>' // Opening paragraph
741 . '(?:' . $spaces . ')*+' // Optional leading whitespace
742 . '(' // 1: The shortcode
743 . '\\[' // Opening bracket
744 . "($tagregexp)" // 2: Shortcode name
745 . '(?![\\w-])' // Not followed by word character or hyphen
746 // Unroll the loop: Inside the opening shortcode tag
747 . '[^\\]\\/]*' // Not a closing bracket or forward slash
749 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
750 . '[^\\]\\/]*' // Not a closing bracket or forward slash
753 . '\\/\\]' // Self closing tag and closing bracket
755 . '\\]' // Closing bracket
756 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
757 . '[^\\[]*+' // Not an opening bracket
759 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
760 . '[^\\[]*+' // Not an opening bracket
762 . '\\[\\/\\2\\]' // Closing shortcode tag
766 . '(?:' . $spaces . ')*+' // optional trailing whitespace
767 . '<\\/p>' // closing paragraph
770 return preg_replace( $pattern, '$1', $pee );
774 * Checks to see if a string is utf8 encoded.
776 * NOTE: This function checks for 5-Byte sequences, UTF8
777 * has Bytes Sequences with a maximum length of 4.
779 * @author bmorel at ssi dot fr (modified)
782 * @param string $str The string to be checked
783 * @return bool True if $str fits a UTF-8 model, false otherwise.
785 function seems_utf8( $str ) {
786 mbstring_binary_safe_encoding();
787 $length = strlen($str);
788 reset_mbstring_encoding();
789 for ($i=0; $i < $length; $i++) {
791 if ($c < 0x80) $n = 0; // 0bbbbbbb
792 elseif (($c & 0xE0) == 0xC0) $n=1; // 110bbbbb
793 elseif (($c & 0xF0) == 0xE0) $n=2; // 1110bbbb
794 elseif (($c & 0xF8) == 0xF0) $n=3; // 11110bbb
795 elseif (($c & 0xFC) == 0xF8) $n=4; // 111110bb
796 elseif (($c & 0xFE) == 0xFC) $n=5; // 1111110b
797 else return false; // Does not match any model
798 for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
799 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
807 * Converts a number of special characters into their HTML entities.
809 * Specifically deals with: &, <, >, ", and '.
811 * $quote_style can be set to ENT_COMPAT to encode " to
812 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
817 * @staticvar string $_charset
819 * @param string $string The text which is to be encoded.
820 * @param int $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
821 * @param string $charset Optional. The character encoding of the string. Default is false.
822 * @param bool $double_encode Optional. Whether to encode existing html entities. Default is false.
823 * @return string The encoded text with HTML entities.
825 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
826 $string = (string) $string;
828 if ( 0 === strlen( $string ) )
831 // Don't bother if there are no specialchars - saves some processing
832 if ( ! preg_match( '/[&<>"\']/', $string ) )
835 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
836 if ( empty( $quote_style ) )
837 $quote_style = ENT_NOQUOTES;
838 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
839 $quote_style = ENT_QUOTES;
841 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
843 static $_charset = null;
844 if ( ! isset( $_charset ) ) {
845 $alloptions = wp_load_alloptions();
846 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
848 $charset = $_charset;
851 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
854 $_quote_style = $quote_style;
856 if ( $quote_style === 'double' ) {
857 $quote_style = ENT_COMPAT;
858 $_quote_style = ENT_COMPAT;
859 } elseif ( $quote_style === 'single' ) {
860 $quote_style = ENT_NOQUOTES;
863 if ( ! $double_encode ) {
864 // Guarantee every &entity; is valid, convert &garbage; into &garbage;
865 // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
866 $string = wp_kses_normalize_entities( $string );
869 $string = @htmlspecialchars( $string, $quote_style, $charset, $double_encode );
871 // Backwards compatibility
872 if ( 'single' === $_quote_style )
873 $string = str_replace( "'", ''', $string );
879 * Converts a number of HTML entities into their special characters.
881 * Specifically deals with: &, <, >, ", and '.
883 * $quote_style can be set to ENT_COMPAT to decode " entities,
884 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
888 * @param string $string The text which is to be decoded.
889 * @param string|int $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
890 * both single and double if set to ENT_QUOTES or
891 * none if set to ENT_NOQUOTES.
892 * Also compatible with old _wp_specialchars() values;
893 * converting single quotes if set to 'single',
894 * double if set to 'double' or both if otherwise set.
895 * Default is ENT_NOQUOTES.
896 * @return string The decoded text without HTML entities.
898 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
899 $string = (string) $string;
901 if ( 0 === strlen( $string ) ) {
905 // Don't bother if there are no entities - saves a lot of processing
906 if ( strpos( $string, '&' ) === false ) {
910 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
911 if ( empty( $quote_style ) ) {
912 $quote_style = ENT_NOQUOTES;
913 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
914 $quote_style = ENT_QUOTES;
917 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
918 $single = array( ''' => '\'', ''' => '\'' );
919 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
920 $double = array( '"' => '"', '"' => '"', '"' => '"' );
921 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
922 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
923 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
925 if ( $quote_style === ENT_QUOTES ) {
926 $translation = array_merge( $single, $double, $others );
927 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
928 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
929 $translation = array_merge( $double, $others );
930 $translation_preg = array_merge( $double_preg, $others_preg );
931 } elseif ( $quote_style === 'single' ) {
932 $translation = array_merge( $single, $others );
933 $translation_preg = array_merge( $single_preg, $others_preg );
934 } elseif ( $quote_style === ENT_NOQUOTES ) {
935 $translation = $others;
936 $translation_preg = $others_preg;
939 // Remove zero padding on numeric entities
940 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
942 // Replace characters according to translation table
943 return strtr( $string, $translation );
947 * Checks for invalid UTF8 in a string.
951 * @staticvar bool $is_utf8
952 * @staticvar bool $utf8_pcre
954 * @param string $string The text which is to be checked.
955 * @param bool $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
956 * @return string The checked text.
958 function wp_check_invalid_utf8( $string, $strip = false ) {
959 $string = (string) $string;
961 if ( 0 === strlen( $string ) ) {
965 // Store the site charset as a static to avoid multiple calls to get_option()
966 static $is_utf8 = null;
967 if ( ! isset( $is_utf8 ) ) {
968 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
974 // Check for support for utf8 in the installed PCRE library once and store the result in a static
975 static $utf8_pcre = null;
976 if ( ! isset( $utf8_pcre ) ) {
977 $utf8_pcre = @preg_match( '/^./u', 'a' );
979 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
984 // preg_match fails when it encounters invalid UTF8 in $string
985 if ( 1 === @preg_match( '/^./us', $string ) ) {
989 // Attempt to strip the bad chars if requested (not recommended)
990 if ( $strip && function_exists( 'iconv' ) ) {
991 return iconv( 'utf-8', 'utf-8', $string );
998 * Encode the Unicode values to be used in the URI.
1002 * @param string $utf8_string
1003 * @param int $length Max length of the string
1004 * @return string String with Unicode encoded for URI.
1006 function utf8_uri_encode( $utf8_string, $length = 0 ) {
1010 $unicode_length = 0;
1012 mbstring_binary_safe_encoding();
1013 $string_length = strlen( $utf8_string );
1014 reset_mbstring_encoding();
1016 for ($i = 0; $i < $string_length; $i++ ) {
1018 $value = ord( $utf8_string[ $i ] );
1020 if ( $value < 128 ) {
1021 if ( $length && ( $unicode_length >= $length ) )
1023 $unicode .= chr($value);
1026 if ( count( $values ) == 0 ) {
1027 if ( $value < 224 ) {
1029 } elseif ( $value < 240 ) {
1038 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
1040 if ( count( $values ) == $num_octets ) {
1041 for ( $j = 0; $j < $num_octets; $j++ ) {
1042 $unicode .= '%' . dechex( $values[ $j ] );
1045 $unicode_length += $num_octets * 3;
1057 * Converts all accent characters to ASCII characters.
1059 * If there are no accent characters, then the string given is just returned.
1063 * @param string $string Text that might have accent characters
1064 * @return string Filtered string with replaced "nice" characters.
1066 function remove_accents( $string ) {
1067 if ( !preg_match('/[\x80-\xff]/', $string) )
1070 if (seems_utf8($string)) {
1072 // Decompositions for Latin-1 Supplement
1073 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
1074 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
1075 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
1076 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
1077 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
1078 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
1079 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
1080 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
1081 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
1082 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
1083 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
1084 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
1085 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
1086 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
1087 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
1088 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
1089 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
1090 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
1091 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
1092 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
1093 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
1094 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
1095 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
1096 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
1097 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
1098 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
1099 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
1100 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
1101 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
1102 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
1103 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
1104 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
1105 // Decompositions for Latin Extended-A
1106 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
1107 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
1108 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
1109 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
1110 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
1111 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
1112 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
1113 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
1114 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
1115 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
1116 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
1117 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
1118 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
1119 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
1120 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
1121 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
1122 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
1123 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
1124 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
1125 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
1126 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
1127 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
1128 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
1129 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
1130 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
1131 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
1132 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
1133 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
1134 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
1135 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
1136 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
1137 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
1138 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
1139 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
1140 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
1141 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
1142 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
1143 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
1144 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
1145 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
1146 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
1147 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
1148 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
1149 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
1150 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
1151 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
1152 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
1153 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
1154 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
1155 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
1156 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
1157 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
1158 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
1159 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
1160 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
1161 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
1162 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
1163 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
1164 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
1165 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
1166 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
1167 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
1168 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
1169 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
1170 // Decompositions for Latin Extended-B
1171 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
1172 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
1174 chr(226).chr(130).chr(172) => 'E',
1176 chr(194).chr(163) => '',
1177 // Vowels with diacritic (Vietnamese)
1179 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
1180 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
1182 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
1183 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
1184 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
1185 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
1186 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
1187 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
1188 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
1190 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
1191 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
1192 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
1193 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
1194 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
1195 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
1196 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
1197 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
1198 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
1199 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
1200 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
1201 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
1203 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
1204 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
1205 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
1206 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
1207 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
1208 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
1209 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
1210 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
1212 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
1213 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
1214 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
1215 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
1216 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
1217 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
1219 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
1220 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
1221 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
1222 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
1223 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
1224 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
1225 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
1226 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
1227 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
1228 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
1229 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
1230 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
1231 // Vowels with diacritic (Chinese, Hanyu Pinyin)
1232 chr(201).chr(145) => 'a',
1234 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
1236 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
1238 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
1239 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
1240 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
1241 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
1242 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
1244 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
1247 // Used for locale-specific rules
1248 $locale = get_locale();
1250 if ( 'de_DE' == $locale || 'de_DE_formal' == $locale ) {
1251 $chars[ chr(195).chr(132) ] = 'Ae';
1252 $chars[ chr(195).chr(164) ] = 'ae';
1253 $chars[ chr(195).chr(150) ] = 'Oe';
1254 $chars[ chr(195).chr(182) ] = 'oe';
1255 $chars[ chr(195).chr(156) ] = 'Ue';
1256 $chars[ chr(195).chr(188) ] = 'ue';
1257 $chars[ chr(195).chr(159) ] = 'ss';
1258 } elseif ( 'da_DK' === $locale ) {
1259 $chars[ chr(195).chr(134) ] = 'Ae';
1260 $chars[ chr(195).chr(166) ] = 'ae';
1261 $chars[ chr(195).chr(152) ] = 'Oe';
1262 $chars[ chr(195).chr(184) ] = 'oe';
1263 $chars[ chr(195).chr(133) ] = 'Aa';
1264 $chars[ chr(195).chr(165) ] = 'aa';
1267 $string = strtr($string, $chars);
1270 // Assume ISO-8859-1 if not UTF-8
1271 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1272 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1273 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1274 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1275 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1276 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1277 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1278 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1279 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1280 .chr(252).chr(253).chr(255);
1282 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1284 $string = strtr($string, $chars['in'], $chars['out']);
1285 $double_chars = array();
1286 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1287 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1288 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1295 * Sanitizes a filename, replacing whitespace with dashes.
1297 * Removes special characters that are illegal in filenames on certain
1298 * operating systems and special characters requiring special escaping
1299 * to manipulate at the command line. Replaces spaces and consecutive
1300 * dashes with a single dash. Trims period, dash and underscore from beginning
1301 * and end of filename.
1305 * @param string $filename The filename to be sanitized
1306 * @return string The sanitized filename
1308 function sanitize_file_name( $filename ) {
1309 $filename_raw = $filename;
1310 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1312 * Filter the list of characters to remove from a filename.
1316 * @param array $special_chars Characters to remove.
1317 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1319 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1320 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1321 $filename = str_replace( $special_chars, '', $filename );
1322 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1323 $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
1324 $filename = trim( $filename, '.-_' );
1326 // Split the filename into a base and extension[s]
1327 $parts = explode('.', $filename);
1329 // Return if only one extension
1330 if ( count( $parts ) <= 2 ) {
1332 * Filter a sanitized filename string.
1336 * @param string $filename Sanitized filename.
1337 * @param string $filename_raw The filename prior to sanitization.
1339 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1342 // Process multiple extensions
1343 $filename = array_shift($parts);
1344 $extension = array_pop($parts);
1345 $mimes = get_allowed_mime_types();
1348 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1349 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1351 foreach ( (array) $parts as $part) {
1352 $filename .= '.' . $part;
1354 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1356 foreach ( $mimes as $ext_preg => $mime_match ) {
1357 $ext_preg = '!^(' . $ext_preg . ')$!i';
1358 if ( preg_match( $ext_preg, $part ) ) {
1367 $filename .= '.' . $extension;
1368 /** This filter is documented in wp-includes/formatting.php */
1369 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1373 * Sanitizes a username, stripping out unsafe characters.
1375 * Removes tags, octets, entities, and if strict is enabled, will only keep
1376 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1377 * raw username (the username in the parameter), and the value of $strict as
1378 * parameters for the 'sanitize_user' filter.
1382 * @param string $username The username to be sanitized.
1383 * @param bool $strict If set limits $username to specific characters. Default false.
1384 * @return string The sanitized username, after passing through filters.
1386 function sanitize_user( $username, $strict = false ) {
1387 $raw_username = $username;
1388 $username = wp_strip_all_tags( $username );
1389 $username = remove_accents( $username );
1391 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1392 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1394 // If strict, reduce to ASCII for max portability.
1396 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1398 $username = trim( $username );
1399 // Consolidate contiguous whitespace
1400 $username = preg_replace( '|\s+|', ' ', $username );
1403 * Filter a sanitized username string.
1407 * @param string $username Sanitized username.
1408 * @param string $raw_username The username prior to sanitization.
1409 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1411 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1415 * Sanitizes a string key.
1417 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1421 * @param string $key String key
1422 * @return string Sanitized key
1424 function sanitize_key( $key ) {
1426 $key = strtolower( $key );
1427 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1430 * Filter a sanitized key string.
1434 * @param string $key Sanitized key.
1435 * @param string $raw_key The key prior to sanitization.
1437 return apply_filters( 'sanitize_key', $key, $raw_key );
1441 * Sanitizes a title, or returns a fallback title.
1443 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1444 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1449 * @param string $title The string to be sanitized.
1450 * @param string $fallback_title Optional. A title to use if $title is empty.
1451 * @param string $context Optional. The operation for which the string is sanitized
1452 * @return string The sanitized string.
1454 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1455 $raw_title = $title;
1457 if ( 'save' == $context )
1458 $title = remove_accents($title);
1461 * Filter a sanitized title string.
1465 * @param string $title Sanitized title.
1466 * @param string $raw_title The title prior to sanitization.
1467 * @param string $context The context for which the title is being sanitized.
1469 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1471 if ( '' === $title || false === $title )
1472 $title = $fallback_title;
1478 * Sanitizes a title with the 'query' context.
1480 * Used for querying the database for a value from URL.
1484 * @param string $title The string to be sanitized.
1485 * @return string The sanitized string.
1487 function sanitize_title_for_query( $title ) {
1488 return sanitize_title( $title, '', 'query' );
1492 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1494 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1495 * Whitespace becomes a dash.
1499 * @param string $title The title to be sanitized.
1500 * @param string $raw_title Optional. Not used.
1501 * @param string $context Optional. The operation for which the string is sanitized.
1502 * @return string The sanitized title.
1504 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1505 $title = strip_tags($title);
1506 // Preserve escaped octets.
1507 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1508 // Remove percent signs that are not part of an octet.
1509 $title = str_replace('%', '', $title);
1511 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1513 if (seems_utf8($title)) {
1514 if (function_exists('mb_strtolower')) {
1515 $title = mb_strtolower($title, 'UTF-8');
1517 $title = utf8_uri_encode($title, 200);
1520 $title = strtolower($title);
1521 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1522 $title = str_replace('.', '-', $title);
1524 if ( 'save' == $context ) {
1525 // Convert nbsp, ndash and mdash to hyphens
1526 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1528 // Strip these characters entirely
1529 $title = str_replace( array(
1533 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1535 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1536 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1537 // copy, reg, deg, hellip and trade
1538 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1540 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1541 // grave accent, macron, caron
1542 '%cc%80', '%cc%84', '%cc%8c',
1545 // Convert times to x
1546 $title = str_replace( '%c3%97', 'x', $title );
1549 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1550 $title = preg_replace('/\s+/', '-', $title);
1551 $title = preg_replace('|-+|', '-', $title);
1552 $title = trim($title, '-');
1558 * Ensures a string is a valid SQL 'order by' clause.
1560 * Accepts one or more columns, with or without a sort order (ASC / DESC).
1561 * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
1563 * Also accepts 'RAND()'.
1567 * @param string $orderby Order by clause to be validated.
1568 * @return string|false Returns $orderby if valid, false otherwise.
1570 function sanitize_sql_orderby( $orderby ) {
1571 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 ) ) {
1578 * Sanitizes an HTML classname to ensure it only contains valid characters.
1580 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1581 * string then it will return the alternative value supplied.
1583 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1587 * @param string $class The classname to be sanitized
1588 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1589 * Defaults to an empty string.
1590 * @return string The sanitized value
1592 function sanitize_html_class( $class, $fallback = '' ) {
1593 //Strip out any % encoded octets
1594 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1596 //Limit to A-Z,a-z,0-9,_,-
1597 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1599 if ( '' == $sanitized )
1600 $sanitized = $fallback;
1603 * Filter a sanitized HTML class string.
1607 * @param string $sanitized The sanitized HTML class.
1608 * @param string $class HTML class before sanitization.
1609 * @param string $fallback The fallback string.
1611 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1615 * Converts lone & characters into `&` (a.k.a. `&`)
1619 * @param string $content String of characters to be converted.
1620 * @param string $deprecated Not used.
1621 * @return string Converted string.
1623 function convert_chars( $content, $deprecated = '' ) {
1624 if ( ! empty( $deprecated ) ) {
1625 _deprecated_argument( __FUNCTION__, '0.71' );
1628 if ( strpos( $content, '&' ) !== false ) {
1629 $content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content );
1636 * Converts invalid Unicode references range to valid range.
1640 * @param string $content String with entities that need converting.
1641 * @return string Converted string.
1643 function convert_invalid_entities( $content ) {
1644 $wp_htmltranswinuni = array(
1645 '€' => '€', // the Euro sign
1647 '‚' => '‚', // these are Windows CP1252 specific characters
1648 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1649 '„' => '„',
1650 '…' => '…',
1651 '†' => '†',
1652 '‡' => '‡',
1653 'ˆ' => 'ˆ',
1654 '‰' => '‰',
1655 'Š' => 'Š',
1656 '‹' => '‹',
1657 'Œ' => 'Œ',
1659 'Ž' => 'Ž',
1662 '‘' => '‘',
1663 '’' => '’',
1664 '“' => '“',
1665 '”' => '”',
1666 '•' => '•',
1667 '–' => '–',
1668 '—' => '—',
1669 '˜' => '˜',
1670 '™' => '™',
1671 'š' => 'š',
1672 '›' => '›',
1673 'œ' => 'œ',
1675 'ž' => 'ž',
1676 'Ÿ' => 'Ÿ'
1679 if ( strpos( $content, '' ) !== false ) {
1680 $content = strtr( $content, $wp_htmltranswinuni );
1687 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1691 * @param string $text Text to be balanced
1692 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1693 * @return string Balanced text
1695 function balanceTags( $text, $force = false ) {
1696 if ( $force || get_option('use_balanceTags') == 1 ) {
1697 return force_balance_tags( $text );
1704 * Balances tags of string using a modified stack.
1708 * @author Leonard Lin <leonard@acm.org>
1710 * @copyright November 4, 2001
1712 * @todo Make better - change loop condition to $text in 1.2
1713 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1714 * 1.1 Fixed handling of append/stack pop order of end text
1715 * Added Cleaning Hooks
1718 * @param string $text Text to be balanced.
1719 * @return string Balanced text.
1721 function force_balance_tags( $text ) {
1722 $tagstack = array();
1726 // Known single-entity/self-closing tags
1727 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1728 // Tags that can be immediately nested within themselves
1729 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1731 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1732 $text = str_replace('< !--', '< !--', $text);
1733 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1734 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1736 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1737 $newtext .= $tagqueue;
1739 $i = strpos($text, $regex[0]);
1740 $l = strlen($regex[0]);
1742 // clear the shifter
1745 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1746 $tag = strtolower(substr($regex[1],1));
1747 // if too many closing tags
1748 if ( $stacksize <= 0 ) {
1750 // or close to be safe $tag = '/' . $tag;
1752 // if stacktop value = tag close value then pop
1753 elseif ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1754 $tag = '</' . $tag . '>'; // Close Tag
1756 array_pop( $tagstack );
1758 } else { // closing tag not at top, search for it
1759 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1760 if ( $tagstack[$j] == $tag ) {
1761 // add tag to tagqueue
1762 for ( $k = $stacksize-1; $k >= $j; $k--) {
1763 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1771 } else { // Begin Tag
1772 $tag = strtolower($regex[1]);
1776 // If it's an empty tag "< >", do nothing
1780 // ElseIf it presents itself as a self-closing tag...
1781 elseif ( substr( $regex[2], -1 ) == '/' ) {
1782 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1783 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1784 if ( ! in_array( $tag, $single_tags ) )
1785 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1787 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1788 elseif ( in_array($tag, $single_tags) ) {
1791 // Else it's not a single-entity tag
1793 // If the top of the stack is the same as the tag we want to push, close previous tag
1794 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1795 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1798 $stacksize = array_push( $tagstack, $tag );
1802 $attributes = $regex[2];
1803 if ( ! empty( $attributes ) && $attributes[0] != '>' )
1804 $attributes = ' ' . $attributes;
1806 $tag = '<' . $tag . $attributes . '>';
1807 //If already queuing a close tag, then put this tag on, too
1808 if ( !empty($tagqueue) ) {
1813 $newtext .= substr($text, 0, $i) . $tag;
1814 $text = substr($text, $i + $l);
1818 $newtext .= $tagqueue;
1820 // Add Remaining text
1824 while( $x = array_pop($tagstack) )
1825 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1827 // WP fix for the bug with HTML comments
1828 $newtext = str_replace("< !--","<!--",$newtext);
1829 $newtext = str_replace("< !--","< !--",$newtext);
1835 * Acts on text which is about to be edited.
1837 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1838 * to convert special characters to HTML entities. If $richedit is set to true,
1839 * it is simply a holder for the 'format_to_edit' filter.
1843 * @param string $content The text about to be edited.
1844 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1845 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1847 function format_to_edit( $content, $richedit = false ) {
1849 * Filter the text to be formatted for editing.
1853 * @param string $content The text, prior to formatting for editing.
1855 $content = apply_filters( 'format_to_edit', $content );
1857 $content = esc_textarea( $content );
1862 * Add leading zeros when necessary.
1864 * If you set the threshold to '4' and the number is '10', then you will get
1865 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1866 * will get back '5000'.
1868 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1869 * and the size of the number. If the number is large enough, then no zeros will
1874 * @param int $number Number to append zeros to if not greater than threshold.
1875 * @param int $threshold Digit places number needs to be to not have zeros added.
1876 * @return string Adds leading zeros to number if needed.
1878 function zeroise( $number, $threshold ) {
1879 return sprintf( '%0' . $threshold . 's', $number );
1883 * Adds backslashes before letters and before a number at the start of a string.
1887 * @param string $string Value to which backslashes will be added.
1888 * @return string String with backslashes inserted.
1890 function backslashit( $string ) {
1891 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1892 $string = '\\\\' . $string;
1893 return addcslashes( $string, 'A..Za..z' );
1897 * Appends a trailing slash.
1899 * Will remove trailing forward and backslashes if it exists already before adding
1900 * a trailing forward slash. This prevents double slashing a string or path.
1902 * The primary use of this is for paths and thus should be used for paths. It is
1903 * not restricted to paths and offers no specific path support.
1907 * @param string $string What to add the trailing slash to.
1908 * @return string String with trailing slash added.
1910 function trailingslashit( $string ) {
1911 return untrailingslashit( $string ) . '/';
1915 * Removes trailing forward slashes and backslashes if they exist.
1917 * The primary use of this is for paths and thus should be used for paths. It is
1918 * not restricted to paths and offers no specific path support.
1922 * @param string $string What to remove the trailing slashes from.
1923 * @return string String without the trailing slashes.
1925 function untrailingslashit( $string ) {
1926 return rtrim( $string, '/\\' );
1930 * Adds slashes to escape strings.
1932 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1933 * http://www.php.net/magic_quotes} for more details.
1937 * @param string $gpc The string returned from HTTP request data.
1938 * @return string Returns a string escaped with slashes.
1940 function addslashes_gpc($gpc) {
1941 if ( get_magic_quotes_gpc() )
1942 $gpc = stripslashes($gpc);
1944 return wp_slash($gpc);
1948 * Navigates through an array and removes slashes from the values.
1950 * If an array is passed, the array_map() function causes a callback to pass the
1951 * value back to the function. The slashes from this value will removed.
1955 * @param mixed $value The value to be stripped.
1956 * @return mixed Stripped value.
1958 function stripslashes_deep( $value ) {
1959 if ( is_array($value) ) {
1960 $value = array_map('stripslashes_deep', $value);
1961 } elseif ( is_object($value) ) {
1962 $vars = get_object_vars( $value );
1963 foreach ($vars as $key=>$data) {
1964 $value->{$key} = stripslashes_deep( $data );
1966 } elseif ( is_string( $value ) ) {
1967 $value = stripslashes($value);
1974 * Navigates through an array and encodes the values to be used in a URL.
1979 * @param array|string $value The array or string to be encoded.
1980 * @return array|string $value The encoded array (or string from the callback).
1982 function urlencode_deep( $value ) {
1983 return is_array( $value ) ? array_map( 'urlencode_deep', $value ) : urlencode( $value );
1987 * Navigates through an array and raw encodes the values to be used in a URL.
1991 * @param array|string $value The array or string to be encoded.
1992 * @return array|string $value The encoded array (or string from the callback).
1994 function rawurlencode_deep( $value ) {
1995 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1999 * Converts email addresses characters to HTML entities to block spam bots.
2003 * @param string $email_address Email address.
2004 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
2005 * @return string Converted email address.
2007 function antispambot( $email_address, $hex_encoding = 0 ) {
2008 $email_no_spam_address = '';
2009 for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
2010 $j = rand( 0, 1 + $hex_encoding );
2012 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
2013 } elseif ( $j == 1 ) {
2014 $email_no_spam_address .= $email_address[$i];
2015 } elseif ( $j == 2 ) {
2016 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
2020 return str_replace( '@', '@', $email_no_spam_address );
2024 * Callback to convert URI match to HTML A element.
2026 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2027 * make_clickable()}.
2032 * @param array $matches Single Regex Match.
2033 * @return string HTML A element with URI address.
2035 function _make_url_clickable_cb( $matches ) {
2038 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
2039 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
2040 // Then we can let the parenthesis balancer do its thing below.
2041 $url .= $matches[3];
2044 $suffix = $matches[3];
2047 // Include parentheses in the URL only if paired
2048 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
2049 $suffix = strrchr( $url, ')' ) . $suffix;
2050 $url = substr( $url, 0, strrpos( $url, ')' ) );
2053 $url = esc_url($url);
2057 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
2061 * Callback to convert URL match to HTML A element.
2063 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2064 * make_clickable()}.
2069 * @param array $matches Single Regex Match.
2070 * @return string HTML A element with URL address.
2072 function _make_web_ftp_clickable_cb( $matches ) {
2074 $dest = $matches[2];
2075 $dest = 'http://' . $dest;
2076 $dest = esc_url($dest);
2080 // removed trailing [.,;:)] from URL
2081 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
2082 $ret = substr($dest, -1);
2083 $dest = substr($dest, 0, strlen($dest)-1);
2085 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
2089 * Callback to convert email address match to HTML A element.
2091 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2092 * make_clickable()}.
2097 * @param array $matches Single Regex Match.
2098 * @return string HTML A element with email address.
2100 function _make_email_clickable_cb( $matches ) {
2101 $email = $matches[2] . '@' . $matches[3];
2102 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
2106 * Convert plaintext URI to HTML links.
2108 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
2113 * @param string $text Content to convert URIs.
2114 * @return string Content with converted URIs.
2116 function make_clickable( $text ) {
2118 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
2119 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
2120 foreach ( $textarr as $piece ) {
2122 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
2124 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
2127 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
2132 // Long strings might contain expensive edge cases ...
2133 if ( 10000 < strlen( $piece ) ) {
2135 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
2136 if ( 2101 < strlen( $chunk ) ) {
2137 $r .= $chunk; // Too big, no whitespace: bail.
2139 $r .= make_clickable( $chunk );
2143 $ret = " $piece "; // Pad with whitespace to simplify the regexes
2146 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
2148 [\\w]{1,20}+:// # Scheme and hier-part prefix
2149 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
2150 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
2151 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
2152 [\'.,;:!?)] # Punctuation URL character
2153 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
2156 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
2157 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
2158 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
2160 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
2162 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
2163 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
2165 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
2170 // Cleanup of accidental links within links
2171 return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
2175 * Breaks a string into chunks by splitting at whitespace characters.
2176 * The length of each returned chunk is as close to the specified length goal as possible,
2177 * with the caveat that each chunk includes its trailing delimiter.
2178 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
2180 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
2182 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
2184 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
2186 * 0 => '1234 67890 ', // 11 characters: Perfect split
2187 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
2188 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
2189 * 3 => '1234 890 ', // 11 characters: Perfect split
2190 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
2191 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
2192 * 6 => ' 45678 ', // 11 characters: Perfect split
2193 * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
2199 * @param string $string The string to split.
2200 * @param int $goal The desired chunk length.
2201 * @return array Numeric array of chunks.
2203 function _split_str_by_whitespace( $string, $goal ) {
2206 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
2208 while ( $goal < strlen( $string_nullspace ) ) {
2209 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
2211 if ( false === $pos ) {
2212 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
2213 if ( false === $pos ) {
2218 $chunks[] = substr( $string, 0, $pos + 1 );
2219 $string = substr( $string, $pos + 1 );
2220 $string_nullspace = substr( $string_nullspace, $pos + 1 );
2224 $chunks[] = $string;
2231 * Adds rel nofollow string to all HTML A elements in content.
2235 * @param string $text Content that may contain HTML A elements.
2236 * @return string Converted content.
2238 function wp_rel_nofollow( $text ) {
2239 // This is a pre save filter, so text is already escaped.
2240 $text = stripslashes($text);
2241 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
2242 return wp_slash( $text );
2246 * Callback to add rel=nofollow string to HTML A element.
2248 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2249 * string to prevent from invalidating (X)HTML.
2253 * @param array $matches Single Match
2254 * @return string HTML A Element with rel nofollow.
2256 function wp_rel_nofollow_callback( $matches ) {
2257 $text = $matches[1];
2258 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
2259 return "<a $text rel=\"nofollow\">";
2263 * Convert one smiley code to the icon graphic file equivalent.
2265 * Callback handler for {@link convert_smilies()}.
2266 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2267 * `<img>` string for that smiley.
2271 * @global array $wpsmiliestrans
2273 * @param array $matches Single match. Smiley code to convert to image.
2274 * @return string Image string for smiley.
2276 function translate_smiley( $matches ) {
2277 global $wpsmiliestrans;
2279 if ( count( $matches ) == 0 )
2282 $smiley = trim( reset( $matches ) );
2283 $img = $wpsmiliestrans[ $smiley ];
2286 $ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
2287 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
2289 // Don't convert smilies that aren't images - they're probably emoji.
2290 if ( ! in_array( $ext, $image_exts ) ) {
2295 * Filter the Smiley image URL before it's used in the image element.
2299 * @param string $smiley_url URL for the smiley image.
2300 * @param string $img Filename for the smiley image.
2301 * @param string $site_url Site URL, as returned by site_url().
2303 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2305 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
2309 * Convert text equivalent of smilies to images.
2311 * Will only convert smilies if the option 'use_smilies' is true and the global
2312 * used in the function isn't empty.
2316 * @global string|array $wp_smiliessearch
2318 * @param string $text Content to convert smilies from text.
2319 * @return string Converted content with text smilies replaced with images.
2321 function convert_smilies( $text ) {
2322 global $wp_smiliessearch;
2324 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2325 // HTML loop taken from texturize function, could possible be consolidated
2326 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2327 $stop = count( $textarr );// loop stuff
2329 // Ignore proessing of specific tags
2330 $tags_to_ignore = 'code|pre|style|script|textarea';
2331 $ignore_block_element = '';
2333 for ( $i = 0; $i < $stop; $i++ ) {
2334 $content = $textarr[$i];
2336 // If we're in an ignore block, wait until we find its closing tag
2337 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2338 $ignore_block_element = $matches[1];
2341 // If it's not a tag and not in ignore block
2342 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2343 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2346 // did we exit ignore block
2347 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2348 $ignore_block_element = '';
2351 $output .= $content;
2354 // return default text.
2361 * Verifies that an email is valid.
2363 * Does not grok i18n domains. Not RFC compliant.
2367 * @param string $email Email address to verify.
2368 * @param bool $deprecated Deprecated.
2369 * @return string|bool Either false or the valid email address.
2371 function is_email( $email, $deprecated = false ) {
2372 if ( ! empty( $deprecated ) )
2373 _deprecated_argument( __FUNCTION__, '3.0' );
2375 // Test for the minimum length the email can be
2376 if ( strlen( $email ) < 3 ) {
2378 * Filter whether an email address is valid.
2380 * This filter is evaluated under several different contexts, such as 'email_too_short',
2381 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2382 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2386 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2387 * @param string $email The email address being checked.
2388 * @param string $message An explanatory message to the user.
2389 * @param string $context Context under which the email was tested.
2391 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2394 // Test for an @ character after the first position
2395 if ( strpos( $email, '@', 1 ) === false ) {
2396 /** This filter is documented in wp-includes/formatting.php */
2397 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2400 // Split out the local and domain parts
2401 list( $local, $domain ) = explode( '@', $email, 2 );
2404 // Test for invalid characters
2405 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2406 /** This filter is documented in wp-includes/formatting.php */
2407 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2411 // Test for sequences of periods
2412 if ( preg_match( '/\.{2,}/', $domain ) ) {
2413 /** This filter is documented in wp-includes/formatting.php */
2414 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2417 // Test for leading and trailing periods and whitespace
2418 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2419 /** This filter is documented in wp-includes/formatting.php */
2420 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2423 // Split the domain into subs
2424 $subs = explode( '.', $domain );
2426 // Assume the domain will have at least two subs
2427 if ( 2 > count( $subs ) ) {
2428 /** This filter is documented in wp-includes/formatting.php */
2429 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2432 // Loop through each sub
2433 foreach ( $subs as $sub ) {
2434 // Test for leading and trailing hyphens and whitespace
2435 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2436 /** This filter is documented in wp-includes/formatting.php */
2437 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2440 // Test for invalid characters
2441 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2442 /** This filter is documented in wp-includes/formatting.php */
2443 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2447 // Congratulations your email made it!
2448 /** This filter is documented in wp-includes/formatting.php */
2449 return apply_filters( 'is_email', $email, $email, null );
2453 * Convert to ASCII from email subjects.
2457 * @param string $string Subject line
2458 * @return string Converted string to ASCII
2460 function wp_iso_descrambler( $string ) {
2461 /* this may only work with iso-8859-1, I'm afraid */
2462 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2465 $subject = str_replace('_', ' ', $matches[2]);
2466 return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
2471 * Helper function to convert hex encoded chars to ASCII
2476 * @param array $match The preg_replace_callback matches array
2477 * @return string Converted chars
2479 function _wp_iso_convert( $match ) {
2480 return chr( hexdec( strtolower( $match[1] ) ) );
2484 * Returns a date in the GMT equivalent.
2486 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2487 * timezone_string available, the date is assumed to be in that timezone,
2488 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2489 * format can be overridden using the $format parameter.
2493 * @param string $string The date to be converted.
2494 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2495 * @return string GMT version of the date provided.
2497 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2498 $tz = get_option( 'timezone_string' );
2500 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2502 return gmdate( $format, 0 );
2503 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2504 $string_gmt = $datetime->format( $format );
2506 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 ) )
2507 return gmdate( $format, 0 );
2508 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2509 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2515 * Converts a GMT date into the correct format for the blog.
2517 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2518 * timezone_string available, the returned date is in that timezone, otherwise
2519 * it simply adds the value of gmt_offset. Return format can be overridden
2520 * using the $format parameter
2524 * @param string $string The date to be converted.
2525 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2526 * @return string Formatted date relative to the timezone / GMT offset.
2528 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2529 $tz = get_option( 'timezone_string' );
2531 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2533 return date( $format, 0 );
2534 $datetime->setTimezone( new DateTimeZone( $tz ) );
2535 $string_localtime = $datetime->format( $format );
2537 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) )
2538 return date( $format, 0 );
2539 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2540 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2542 return $string_localtime;
2546 * Computes an offset in seconds from an iso8601 timezone.
2550 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2551 * @return int|float The offset in seconds.
2553 function iso8601_timezone_to_offset( $timezone ) {
2554 // $timezone is either 'Z' or '[+|-]hhmm'
2555 if ($timezone == 'Z') {
2558 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2559 $hours = intval(substr($timezone, 1, 2));
2560 $minutes = intval(substr($timezone, 3, 4)) / 60;
2561 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2567 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2571 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2572 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2573 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2575 function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
2576 $timezone = strtolower($timezone);
2578 if ($timezone == 'gmt') {
2580 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);
2582 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2583 $offset = iso8601_timezone_to_offset($date_bits[7]);
2584 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2585 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2588 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2589 $timestamp -= $offset;
2591 return gmdate('Y-m-d H:i:s', $timestamp);
2593 } elseif ($timezone == 'user') {
2594 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);
2599 * Adds a element attributes to open links in new windows.
2601 * Comment text in popup windows should be filtered through this. Right now it's
2602 * a moderately dumb function, ideally it would detect whether a target or rel
2603 * attribute was already there and adjust its actions accordingly.
2607 * @param string $text Content to replace links to open in a new window.
2608 * @return string Content that has filtered links.
2610 function popuplinks( $text ) {
2611 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2616 * Strips out all characters that are not allowable in an email.
2620 * @param string $email Email address to filter.
2621 * @return string Filtered email address.
2623 function sanitize_email( $email ) {
2624 // Test for the minimum length the email can be
2625 if ( strlen( $email ) < 3 ) {
2627 * Filter a sanitized email address.
2629 * This filter is evaluated under several contexts, including 'email_too_short',
2630 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2631 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2635 * @param string $email The sanitized email address.
2636 * @param string $email The email address, as provided to sanitize_email().
2637 * @param string $message A message to pass to the user.
2639 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2642 // Test for an @ character after the first position
2643 if ( strpos( $email, '@', 1 ) === false ) {
2644 /** This filter is documented in wp-includes/formatting.php */
2645 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2648 // Split out the local and domain parts
2649 list( $local, $domain ) = explode( '@', $email, 2 );
2652 // Test for invalid characters
2653 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2654 if ( '' === $local ) {
2655 /** This filter is documented in wp-includes/formatting.php */
2656 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2660 // Test for sequences of periods
2661 $domain = preg_replace( '/\.{2,}/', '', $domain );
2662 if ( '' === $domain ) {
2663 /** This filter is documented in wp-includes/formatting.php */
2664 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2667 // Test for leading and trailing periods and whitespace
2668 $domain = trim( $domain, " \t\n\r\0\x0B." );
2669 if ( '' === $domain ) {
2670 /** This filter is documented in wp-includes/formatting.php */
2671 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2674 // Split the domain into subs
2675 $subs = explode( '.', $domain );
2677 // Assume the domain will have at least two subs
2678 if ( 2 > count( $subs ) ) {
2679 /** This filter is documented in wp-includes/formatting.php */
2680 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2683 // Create an array that will contain valid subs
2684 $new_subs = array();
2686 // Loop through each sub
2687 foreach ( $subs as $sub ) {
2688 // Test for leading and trailing hyphens
2689 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2691 // Test for invalid characters
2692 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2694 // If there's anything left, add it to the valid subs
2695 if ( '' !== $sub ) {
2700 // If there aren't 2 or more valid subs
2701 if ( 2 > count( $new_subs ) ) {
2702 /** This filter is documented in wp-includes/formatting.php */
2703 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2706 // Join valid subs into the new domain
2707 $domain = join( '.', $new_subs );
2709 // Put the email back together
2710 $email = $local . '@' . $domain;
2712 // Congratulations your email made it!
2713 /** This filter is documented in wp-includes/formatting.php */
2714 return apply_filters( 'sanitize_email', $email, $email, null );
2718 * Determines the difference between two timestamps.
2720 * The difference is returned in a human readable format such as "1 hour",
2721 * "5 mins", "2 days".
2725 * @param int $from Unix timestamp from which the difference begins.
2726 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2727 * @return string Human readable time difference.
2729 function human_time_diff( $from, $to = '' ) {
2730 if ( empty( $to ) ) {
2734 $diff = (int) abs( $to - $from );
2736 if ( $diff < HOUR_IN_SECONDS ) {
2737 $mins = round( $diff / MINUTE_IN_SECONDS );
2740 /* translators: min=minute */
2741 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2742 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2743 $hours = round( $diff / HOUR_IN_SECONDS );
2746 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2747 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2748 $days = round( $diff / DAY_IN_SECONDS );
2751 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2752 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2753 $weeks = round( $diff / WEEK_IN_SECONDS );
2756 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2757 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2758 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2761 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2762 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2763 $years = round( $diff / YEAR_IN_SECONDS );
2766 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2770 * Filter the human readable difference between two timestamps.
2774 * @param string $since The difference in human readable text.
2775 * @param int $diff The difference in seconds.
2776 * @param int $from Unix timestamp from which the difference begins.
2777 * @param int $to Unix timestamp to end the time difference.
2779 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2783 * Generates an excerpt from the content, if needed.
2785 * The excerpt word amount will be 55 words and if the amount is greater than
2786 * that, then the string ' […]' will be appended to the excerpt. If the string
2787 * is less than 55 words, then the content will be returned as is.
2789 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2790 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2794 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2795 * @return string The excerpt.
2797 function wp_trim_excerpt( $text = '' ) {
2798 $raw_excerpt = $text;
2799 if ( '' == $text ) {
2800 $text = get_the_content('');
2802 $text = strip_shortcodes( $text );
2804 /** This filter is documented in wp-includes/post-template.php */
2805 $text = apply_filters( 'the_content', $text );
2806 $text = str_replace(']]>', ']]>', $text);
2809 * Filter the number of words in an excerpt.
2813 * @param int $number The number of words. Default 55.
2815 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2817 * Filter the string in the "more" link displayed after a trimmed excerpt.
2821 * @param string $more_string The string shown within the more link.
2823 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2824 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2827 * Filter the trimmed excerpt string.
2831 * @param string $text The trimmed text.
2832 * @param string $raw_excerpt The text prior to trimming.
2834 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2838 * Trims text to a certain number of words.
2840 * This function is localized. For languages that count 'words' by the individual
2841 * character (such as East Asian languages), the $num_words argument will apply
2842 * to the number of individual characters.
2846 * @param string $text Text to trim.
2847 * @param int $num_words Number of words. Default 55.
2848 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2849 * @return string Trimmed text.
2851 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2852 if ( null === $more ) {
2853 $more = __( '…' );
2856 $original_text = $text;
2857 $text = wp_strip_all_tags( $text );
2860 * translators: If your word count is based on single characters (e.g. East Asian characters),
2861 * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
2862 * Do not translate into your own language.
2864 if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2865 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2866 preg_match_all( '/./u', $text, $words_array );
2867 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2870 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2874 if ( count( $words_array ) > $num_words ) {
2875 array_pop( $words_array );
2876 $text = implode( $sep, $words_array );
2877 $text = $text . $more;
2879 $text = implode( $sep, $words_array );
2883 * Filter the text content after words have been trimmed.
2887 * @param string $text The trimmed text.
2888 * @param int $num_words The number of words to trim the text to. Default 5.
2889 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2890 * @param string $original_text The text before it was trimmed.
2892 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2896 * Converts named entities into numbered entities.
2900 * @param string $text The text within which entities will be converted.
2901 * @return string Text with converted entities.
2903 function ent2ncr( $text ) {
2906 * Filter text before named entities are converted into numbered entities.
2908 * A non-null string must be returned for the filter to be evaluated.
2912 * @param null $converted_text The text to be converted. Default null.
2913 * @param string $text The text prior to entity conversion.
2915 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2916 if ( null !== $filtered )
2920 '"' => '"',
2925 ' ' => ' ',
2926 '¡' => '¡',
2927 '¢' => '¢',
2928 '£' => '£',
2929 '¤' => '¤',
2930 '¥' => '¥',
2931 '¦' => '¦',
2932 '&brkbar;' => '¦',
2933 '§' => '§',
2934 '¨' => '¨',
2935 '¨' => '¨',
2936 '©' => '©',
2937 'ª' => 'ª',
2938 '«' => '«',
2939 '¬' => '¬',
2940 '­' => '­',
2941 '®' => '®',
2942 '¯' => '¯',
2943 '&hibar;' => '¯',
2944 '°' => '°',
2945 '±' => '±',
2946 '²' => '²',
2947 '³' => '³',
2948 '´' => '´',
2949 'µ' => 'µ',
2950 '¶' => '¶',
2951 '·' => '·',
2952 '¸' => '¸',
2953 '¹' => '¹',
2954 'º' => 'º',
2955 '»' => '»',
2956 '¼' => '¼',
2957 '½' => '½',
2958 '¾' => '¾',
2959 '¿' => '¿',
2960 'À' => 'À',
2961 'Á' => 'Á',
2962 'Â' => 'Â',
2963 'Ã' => 'Ã',
2964 'Ä' => 'Ä',
2965 'Å' => 'Å',
2966 'Æ' => 'Æ',
2967 'Ç' => 'Ç',
2968 'È' => 'È',
2969 'É' => 'É',
2970 'Ê' => 'Ê',
2971 'Ë' => 'Ë',
2972 'Ì' => 'Ì',
2973 'Í' => 'Í',
2974 'Î' => 'Î',
2975 'Ï' => 'Ï',
2976 'Ð' => 'Ð',
2977 'Ñ' => 'Ñ',
2978 'Ò' => 'Ò',
2979 'Ó' => 'Ó',
2980 'Ô' => 'Ô',
2981 'Õ' => 'Õ',
2982 'Ö' => 'Ö',
2983 '×' => '×',
2984 'Ø' => 'Ø',
2985 'Ù' => 'Ù',
2986 'Ú' => 'Ú',
2987 'Û' => 'Û',
2988 'Ü' => 'Ü',
2989 'Ý' => 'Ý',
2990 'Þ' => 'Þ',
2991 'ß' => 'ß',
2992 'à' => 'à',
2993 'á' => 'á',
2994 'â' => 'â',
2995 'ã' => 'ã',
2996 'ä' => 'ä',
2997 'å' => 'å',
2998 'æ' => 'æ',
2999 'ç' => 'ç',
3000 'è' => 'è',
3001 'é' => 'é',
3002 'ê' => 'ê',
3003 'ë' => 'ë',
3004 'ì' => 'ì',
3005 'í' => 'í',
3006 'î' => 'î',
3007 'ï' => 'ï',
3008 'ð' => 'ð',
3009 'ñ' => 'ñ',
3010 'ò' => 'ò',
3011 'ó' => 'ó',
3012 'ô' => 'ô',
3013 'õ' => 'õ',
3014 'ö' => 'ö',
3015 '÷' => '÷',
3016 'ø' => 'ø',
3017 'ù' => 'ù',
3018 'ú' => 'ú',
3019 'û' => 'û',
3020 'ü' => 'ü',
3021 'ý' => 'ý',
3022 'þ' => 'þ',
3023 'ÿ' => 'ÿ',
3024 'Œ' => 'Œ',
3025 'œ' => 'œ',
3026 'Š' => 'Š',
3027 'š' => 'š',
3028 'Ÿ' => 'Ÿ',
3029 'ƒ' => 'ƒ',
3030 'ˆ' => 'ˆ',
3031 '˜' => '˜',
3032 'Α' => 'Α',
3033 'Β' => 'Β',
3034 'Γ' => 'Γ',
3035 'Δ' => 'Δ',
3036 'Ε' => 'Ε',
3037 'Ζ' => 'Ζ',
3038 'Η' => 'Η',
3039 'Θ' => 'Θ',
3040 'Ι' => 'Ι',
3041 'Κ' => 'Κ',
3042 'Λ' => 'Λ',
3046 'Ο' => 'Ο',
3048 'Ρ' => 'Ρ',
3049 'Σ' => 'Σ',
3050 'Τ' => 'Τ',
3051 'Υ' => 'Υ',
3052 'Φ' => 'Φ',
3053 'Χ' => 'Χ',
3054 'Ψ' => 'Ψ',
3055 'Ω' => 'Ω',
3056 'α' => 'α',
3057 'β' => 'β',
3058 'γ' => 'γ',
3059 'δ' => 'δ',
3060 'ε' => 'ε',
3061 'ζ' => 'ζ',
3062 'η' => 'η',
3063 'θ' => 'θ',
3064 'ι' => 'ι',
3065 'κ' => 'κ',
3066 'λ' => 'λ',
3070 'ο' => 'ο',
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 '∝' => '∝',
3136 '∞' => '∞',
3137 '∠' => '∠',
3138 '∧' => '∧',
3139 '∨' => '∨',
3140 '∩' => '∩',
3141 '∪' => '∪',
3142 '∫' => '∫',
3143 '∴' => '∴',
3144 '∼' => '∼',
3145 '≅' => '≅',
3146 '≈' => '≈',
3147 '≠' => '≠',
3148 '≡' => '≡',
3149 '≤' => '≤',
3150 '≥' => '≥',
3151 '⊂' => '⊂',
3152 '⊃' => '⊃',
3153 '⊄' => '⊄',
3154 '⊆' => '⊆',
3155 '⊇' => '⊇',
3156 '⊕' => '⊕',
3157 '⊗' => '⊗',
3158 '⊥' => '⊥',
3159 '⋅' => '⋅',
3160 '⌈' => '⌈',
3161 '⌉' => '⌉',
3162 '⌊' => '⌊',
3163 '⌋' => '⌋',
3164 '⟨' => '〈',
3165 '⟩' => '〉',
3166 '←' => '←',
3167 '↑' => '↑',
3168 '→' => '→',
3169 '↓' => '↓',
3170 '↔' => '↔',
3171 '◊' => '◊',
3172 '♠' => '♠',
3173 '♣' => '♣',
3174 '♥' => '♥',
3175 '♦' => '♦'
3178 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
3182 * Formats text for the editor.
3184 * Generally the browsers treat everything inside a textarea as text, but
3185 * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
3187 * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
3188 * filter will be applied to an empty string.
3192 * @param string $text The text to be formatted.
3193 * @return string The formatted text after filter is applied.
3195 function format_for_editor( $text, $default_editor = null ) {
3197 $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
3201 * Filter the text after it is formatted for the editor.
3205 * @param string $text The formatted text.
3207 return apply_filters( 'format_for_editor', $text, $default_editor );
3211 * Perform a deep string replace operation to ensure the values in $search are no longer present
3213 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
3214 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
3215 * str_replace would return
3220 * @param string|array $search The value being searched for, otherwise known as the needle.
3221 * An array may be used to designate multiple needles.
3222 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
3223 * @return string The string with the replaced svalues.
3225 function _deep_replace( $search, $subject ) {
3226 $subject = (string) $subject;
3230 $subject = str_replace( $search, '', $subject, $count );
3237 * Escapes data for use in a MySQL query.
3239 * Usually you should prepare queries using wpdb::prepare().
3240 * Sometimes, spot-escaping is required or useful. One example
3241 * is preparing an array for use in an IN clause.
3245 * @global wpdb $wpdb
3247 * @param string|array $data Unescaped data
3248 * @return string|array Escaped data
3250 function esc_sql( $data ) {
3252 return $wpdb->_escape( $data );
3256 * Checks and cleans a URL.
3258 * A number of characters are removed from the URL. If the URL is for displaying
3259 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3260 * is applied to the returned cleaned URL.
3264 * @param string $url The URL to be cleaned.
3265 * @param array $protocols Optional. An array of acceptable protocols.
3266 * Defaults to return value of wp_allowed_protocols()
3267 * @param string $_context Private. Use esc_url_raw() for database usage.
3268 * @return string The cleaned $url after the 'clean_url' filter is applied.
3270 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3271 $original_url = $url;
3275 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3276 if ( 0 !== stripos( $url, 'mailto:' ) ) {
3277 $strip = array('%0d', '%0a', '%0D', '%0A');
3278 $url = _deep_replace($strip, $url);
3280 $url = str_replace(';//', '://', $url);
3281 /* If the URL doesn't appear to contain a scheme, we
3282 * presume it needs http:// appended (unless a relative
3283 * link starting with /, # or ? or a php file).
3285 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3286 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3287 $url = 'http://' . $url;
3289 // Replace ampersands and single quotes only when displaying.
3290 if ( 'display' == $_context ) {
3291 $url = wp_kses_normalize_entities( $url );
3292 $url = str_replace( '&', '&', $url );
3293 $url = str_replace( "'", ''', $url );
3296 if ( '/' === $url[0] ) {
3297 $good_protocol_url = $url;
3299 if ( ! is_array( $protocols ) )
3300 $protocols = wp_allowed_protocols();
3301 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3302 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3307 * Filter a string cleaned and escaped for output as a URL.
3311 * @param string $good_protocol_url The cleaned URL to be returned.
3312 * @param string $original_url The URL prior to cleaning.
3313 * @param string $_context If 'display', replace ampersands and single quotes only.
3315 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3319 * Performs esc_url() for database usage.
3323 * @param string $url The URL to be cleaned.
3324 * @param array $protocols An array of acceptable protocols.
3325 * @return string The cleaned URL.
3327 function esc_url_raw( $url, $protocols = null ) {
3328 return esc_url( $url, $protocols, 'db' );
3332 * Convert entities, while preserving already-encoded entities.
3334 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3338 * @param string $myHTML The text to be converted.
3339 * @return string Converted text.
3341 function htmlentities2( $myHTML ) {
3342 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3343 $translation_table[chr(38)] = '&';
3344 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3348 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3350 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3351 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3352 * be in single quotes. The filter 'js_escape' is also applied here.
3356 * @param string $text The text to be escaped.
3357 * @return string Escaped text.
3359 function esc_js( $text ) {
3360 $safe_text = wp_check_invalid_utf8( $text );
3361 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3362 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3363 $safe_text = str_replace( "\r", '', $safe_text );
3364 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3366 * Filter a string cleaned and escaped for output in JavaScript.
3368 * Text passed to esc_js() is stripped of invalid or special characters,
3369 * and properly slashed for output.
3373 * @param string $safe_text The text after it has been escaped.
3374 * @param string $text The text prior to being escaped.
3376 return apply_filters( 'js_escape', $safe_text, $text );
3380 * Escaping for HTML blocks.
3384 * @param string $text
3387 function esc_html( $text ) {
3388 $safe_text = wp_check_invalid_utf8( $text );
3389 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3391 * Filter a string cleaned and escaped for output in HTML.
3393 * Text passed to esc_html() is stripped of invalid or special characters
3398 * @param string $safe_text The text after it has been escaped.
3399 * @param string $text The text prior to being escaped.
3401 return apply_filters( 'esc_html', $safe_text, $text );
3405 * Escaping for HTML attributes.
3409 * @param string $text
3412 function esc_attr( $text ) {
3413 $safe_text = wp_check_invalid_utf8( $text );
3414 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3416 * Filter a string cleaned and escaped for output in an HTML attribute.
3418 * Text passed to esc_attr() is stripped of invalid or special characters
3423 * @param string $safe_text The text after it has been escaped.
3424 * @param string $text The text prior to being escaped.
3426 return apply_filters( 'attribute_escape', $safe_text, $text );
3430 * Escaping for textarea values.
3434 * @param string $text
3437 function esc_textarea( $text ) {
3438 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3440 * Filter a string cleaned and escaped for output in a textarea element.
3444 * @param string $safe_text The text after it has been escaped.
3445 * @param string $text The text prior to being escaped.
3447 return apply_filters( 'esc_textarea', $safe_text, $text );
3451 * Escape an HTML tag name.
3455 * @param string $tag_name
3458 function tag_escape( $tag_name ) {
3459 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3461 * Filter a string cleaned and escaped for output as an HTML tag.
3465 * @param string $safe_tag The tag name after it has been escaped.
3466 * @param string $tag_name The text before it was escaped.
3468 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3472 * Convert full URL paths to absolute paths.
3474 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3475 * beginning, so it isn't a true relative link, but from the web root base.
3478 * @since 4.1.0 Support was added for relative URLs.
3480 * @param string $link Full URL path.
3481 * @return string Absolute path.
3483 function wp_make_link_relative( $link ) {
3484 return preg_replace( '|^(https?:)?//[^/]+(/.*)|i', '$2', $link );
3488 * Sanitises various option values based on the nature of the option.
3490 * This is basically a switch statement which will pass $value through a number
3491 * of functions depending on the $option.
3495 * @global wpdb $wpdb
3497 * @param string $option The name of the option.
3498 * @param string $value The unsanitised value.
3499 * @return string Sanitized value.
3501 function sanitize_option( $option, $value ) {
3504 $original_value = $value;
3507 switch ( $option ) {
3508 case 'admin_email' :
3509 case 'new_admin_email' :
3510 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3511 if ( is_wp_error( $value ) ) {
3512 $error = $value->get_error_message();
3514 $value = sanitize_email( $value );
3515 if ( ! is_email( $value ) ) {
3516 $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
3521 case 'thumbnail_size_w':
3522 case 'thumbnail_size_h':
3523 case 'medium_size_w':
3524 case 'medium_size_h':
3525 case 'large_size_w':
3526 case 'large_size_h':
3527 case 'mailserver_port':
3528 case 'comment_max_links':
3529 case 'page_on_front':
3530 case 'page_for_posts':
3531 case 'rss_excerpt_length':
3532 case 'default_category':
3533 case 'default_email_category':
3534 case 'default_link_category':
3535 case 'close_comments_days_old':
3536 case 'comments_per_page':
3537 case 'thread_comments_depth':
3538 case 'users_can_register':
3539 case 'start_of_week':
3541 $value = absint( $value );
3544 case 'posts_per_page':
3545 case 'posts_per_rss':
3546 $value = (int) $value;
3547 if ( empty($value) )
3550 $value = abs($value);
3553 case 'default_ping_status':
3554 case 'default_comment_status':
3555 // Options that if not there have 0 value but need to be something like "closed"
3556 if ( $value == '0' || $value == '')
3560 case 'blogdescription':
3562 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3563 if ( is_wp_error( $value ) ) {
3564 $error = $value->get_error_message();
3566 $value = wp_kses_post( $value );
3567 $value = esc_html( $value );
3571 case 'blog_charset':
3572 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3576 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3577 if ( null === $value )
3580 $value = intval( $value );
3585 case 'mailserver_url':
3586 case 'mailserver_login':
3587 case 'mailserver_pass':
3589 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3590 if ( is_wp_error( $value ) ) {
3591 $error = $value->get_error_message();
3593 $value = strip_tags( $value );
3594 $value = wp_kses_data( $value );
3599 $value = explode( "\n", $value );
3600 $value = array_filter( array_map( 'trim', $value ) );
3601 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3602 $value = implode( "\n", $value );
3606 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3610 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3611 if ( is_wp_error( $value ) ) {
3612 $error = $value->get_error_message();
3614 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3615 $value = esc_url_raw( $value );
3617 $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3623 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3624 if ( is_wp_error( $value ) ) {
3625 $error = $value->get_error_message();
3627 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3628 $value = esc_url_raw( $value );
3630 $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3636 $allowed = get_available_languages();
3637 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3638 $allowed[] = WPLANG;
3640 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3641 $value = get_option( $option );
3645 case 'illegal_names':
3646 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3647 if ( is_wp_error( $value ) ) {
3648 $error = $value->get_error_message();
3650 if ( ! is_array( $value ) )
3651 $value = explode( ' ', $value );
3653 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3660 case 'limited_email_domains':
3661 case 'banned_email_domains':
3662 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3663 if ( is_wp_error( $value ) ) {
3664 $error = $value->get_error_message();
3666 if ( ! is_array( $value ) )
3667 $value = explode( "\n", $value );
3669 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3672 foreach ( $domains as $domain ) {
3673 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
3682 case 'timezone_string':
3683 $allowed_zones = timezone_identifiers_list();
3684 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3685 $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
3689 case 'permalink_structure':
3690 case 'category_base':
3692 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3693 if ( is_wp_error( $value ) ) {
3694 $error = $value->get_error_message();
3696 $value = esc_url_raw( $value );
3697 $value = str_replace( 'http://', '', $value );
3701 case 'default_role' :
3702 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3703 $value = 'subscriber';
3706 case 'moderation_keys':
3707 case 'blacklist_keys':
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 = explode( "\n", $value );
3713 $value = array_filter( array_map( 'trim', $value ) );
3714 $value = array_unique( $value );
3715 $value = implode( "\n", $value );
3720 if ( ! empty( $error ) ) {
3721 $value = get_option( $option );
3722 if ( function_exists( 'add_settings_error' ) ) {
3723 add_settings_error( $option, "invalid_{$option}", $error );
3728 * Filter an option value following sanitization.
3731 * @since 4.3.0 Added the `$original_value` parameter.
3733 * @param string $value The sanitized option value.
3734 * @param string $option The option name.
3735 * @param string $original_value The original value passed to the function.
3737 return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
3741 * Parses a string into variables to be stored in an array.
3743 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3744 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3748 * @param string $string The string to be parsed.
3749 * @param array $array Variables will be stored in this array.
3751 function wp_parse_str( $string, &$array ) {
3752 parse_str( $string, $array );
3753 if ( get_magic_quotes_gpc() )
3754 $array = stripslashes_deep( $array );
3756 * Filter the array of variables derived from a parsed string.
3760 * @param array $array The array populated with variables.
3762 $array = apply_filters( 'wp_parse_str', $array );
3766 * Convert lone less than signs.
3768 * KSES already converts lone greater than signs.
3772 * @param string $text Text to be converted.
3773 * @return string Converted text.
3775 function wp_pre_kses_less_than( $text ) {
3776 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3780 * Callback function used by preg_replace.
3784 * @param array $matches Populated by matches to preg_replace.
3785 * @return string The text returned after esc_html if needed.
3787 function wp_pre_kses_less_than_callback( $matches ) {
3788 if ( false === strpos($matches[0], '>') )
3789 return esc_html($matches[0]);
3794 * WordPress implementation of PHP sprintf() with filters.
3797 * @link http://www.php.net/sprintf
3799 * @param string $pattern The string which formatted args are inserted.
3800 * @param mixed $args ,... Arguments to be formatted into the $pattern string.
3801 * @return string The formatted string.
3803 function wp_sprintf( $pattern ) {
3804 $args = func_get_args();
3805 $len = strlen($pattern);
3809 while ( $len > $start ) {
3810 // Last character: append and break
3811 if ( strlen($pattern) - 1 == $start ) {
3812 $result .= substr($pattern, -1);
3816 // Literal %: append and continue
3817 if ( substr($pattern, $start, 2) == '%%' ) {
3823 // Get fragment before next %
3824 $end = strpos($pattern, '%', $start + 1);
3825 if ( false === $end )
3827 $fragment = substr($pattern, $start, $end - $start);
3829 // Fragment has a specifier
3830 if ( $pattern[$start] == '%' ) {
3831 // Find numbered arguments or take the next one in order
3832 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3833 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3834 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3837 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3841 * Filter a fragment from the pattern passed to wp_sprintf().
3843 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3847 * @param string $fragment A fragment from the pattern.
3848 * @param string $arg The argument.
3850 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3851 if ( $_fragment != $fragment )
3852 $fragment = $_fragment;
3854 $fragment = sprintf($fragment, strval($arg) );
3857 // Append to result and move to next fragment
3858 $result .= $fragment;
3865 * Localize list items before the rest of the content.
3867 * The '%l' must be at the first characters can then contain the rest of the
3868 * content. The list items will have ', ', ', and', and ' and ' added depending
3869 * on the amount of list items in the $args parameter.
3873 * @param string $pattern Content containing '%l' at the beginning.
3874 * @param array $args List items to prepend to the content and replace '%l'.
3875 * @return string Localized list items and rest of the content.
3877 function wp_sprintf_l( $pattern, $args ) {
3879 if ( substr($pattern, 0, 2) != '%l' )
3882 // Nothing to work with
3887 * Filter the translated delimiters used by wp_sprintf_l().
3888 * Placeholders (%s) are included to assist translators and then
3889 * removed before the array of strings reaches the filter.
3891 * Please note: Ampersands and entities should be avoided here.
3895 * @param array $delimiters An array of translated delimiters.
3897 $l = apply_filters( 'wp_sprintf_l', array(
3898 /* translators: used to join items in a list with more than 2 items */
3899 'between' => sprintf( __('%s, %s'), '', '' ),
3900 /* translators: used to join last two items in a list with more than 2 times */
3901 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3902 /* translators: used to join items in a list with only 2 items */
3903 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3906 $args = (array) $args;
3907 $result = array_shift($args);
3908 if ( count($args) == 1 )
3909 $result .= $l['between_only_two'] . array_shift($args);
3910 // Loop when more than two args
3913 $arg = array_shift($args);
3916 $result .= $l['between_last_two'] . $arg;
3918 $result .= $l['between'] . $arg;
3920 return $result . substr($pattern, 2);
3924 * Safely extracts not more than the first $count characters from html string.
3926 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3927 * be counted as one character. For example & will be counted as 4, < as
3932 * @param string $str String to get the excerpt from.
3933 * @param int $count Maximum number of characters to take.
3934 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3935 * @return string The excerpt.
3937 function wp_html_excerpt( $str, $count, $more = null ) {
3938 if ( null === $more )
3940 $str = wp_strip_all_tags( $str, true );
3941 $excerpt = mb_substr( $str, 0, $count );
3942 // remove part of an entity at the end
3943 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3944 if ( $str != $excerpt )
3945 $excerpt = trim( $excerpt ) . $more;
3950 * Add a Base url to relative links in passed content.
3952 * By default it supports the 'src' and 'href' attributes. However this can be
3953 * changed via the 3rd param.
3957 * @global string $_links_add_base
3959 * @param string $content String to search for links in.
3960 * @param string $base The base URL to prefix to links.
3961 * @param array $attrs The attributes which should be processed.
3962 * @return string The processed content.
3964 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3965 global $_links_add_base;
3966 $_links_add_base = $base;
3967 $attrs = implode('|', (array)$attrs);
3968 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3972 * Callback to add a base url to relative links in passed content.
3977 * @global string $_links_add_base
3979 * @param string $m The matched link.
3980 * @return string The processed link.
3982 function _links_add_base( $m ) {
3983 global $_links_add_base;
3984 //1 = attribute name 2 = quotation mark 3 = URL
3985 return $m[1] . '=' . $m[2] .
3986 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3988 WP_HTTP::make_absolute_url( $m[3], $_links_add_base )
3994 * Adds a Target attribute to all links in passed content.
3996 * This function by default only applies to `<a>` tags, however this can be
3997 * modified by the 3rd param.
3999 * *NOTE:* Any current target attributed will be stripped and replaced.
4003 * @global string $_links_add_target
4005 * @param string $content String to search for links in.
4006 * @param string $target The Target to add to the links.
4007 * @param array $tags An array of tags to apply to.
4008 * @return string The processed content.
4010 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
4011 global $_links_add_target;
4012 $_links_add_target = $target;
4013 $tags = implode('|', (array)$tags);
4014 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
4018 * Callback to add a target attribute to all links in passed content.
4023 * @global string $_links_add_target
4025 * @param string $m The matched link.
4026 * @return string The processed link.
4028 function _links_add_target( $m ) {
4029 global $_links_add_target;
4031 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
4032 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
4036 * Normalize EOL characters and strip duplicate whitespace.
4040 * @param string $str The string to normalize.
4041 * @return string The normalized string.
4043 function normalize_whitespace( $str ) {
4044 $str = trim( $str );
4045 $str = str_replace( "\r", "\n", $str );
4046 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
4051 * Properly strip all HTML tags including script and style
4053 * This differs from strip_tags() because it removes the contents of
4054 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
4055 * will return 'something'. wp_strip_all_tags will return ''
4059 * @param string $string String containing HTML tags
4060 * @param bool $remove_breaks Optional. Whether to remove left over line breaks and white space chars
4061 * @return string The processed string.
4063 function wp_strip_all_tags($string, $remove_breaks = false) {
4064 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
4065 $string = strip_tags($string);
4067 if ( $remove_breaks )
4068 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
4070 return trim( $string );
4074 * Sanitize a string from user input or from the db
4076 * check for invalid UTF-8,
4077 * Convert single < characters to entity,
4079 * remove line breaks, tabs and extra white space,
4084 * @param string $str
4087 function sanitize_text_field( $str ) {
4088 $filtered = wp_check_invalid_utf8( $str );
4090 if ( strpos($filtered, '<') !== false ) {
4091 $filtered = wp_pre_kses_less_than( $filtered );
4092 // This will strip extra whitespace for us.
4093 $filtered = wp_strip_all_tags( $filtered, true );
4095 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
4099 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
4100 $filtered = str_replace($match[0], '', $filtered);
4105 // Strip out the whitespace that may now exist after removing the octets.
4106 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
4110 * Filter a sanitized text field string.
4114 * @param string $filtered The sanitized string.
4115 * @param string $str The string prior to being sanitized.
4117 return apply_filters( 'sanitize_text_field', $filtered, $str );
4121 * i18n friendly version of basename()
4125 * @param string $path A path.
4126 * @param string $suffix If the filename ends in suffix this will also be cut off.
4129 function wp_basename( $path, $suffix = '' ) {
4130 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
4134 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
4136 * Violating our coding standards for a good function name.
4140 * @staticvar string|false $dblq
4142 function capital_P_dangit( $text ) {
4143 // Simple replacement for titles
4144 $current_filter = current_filter();
4145 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
4146 return str_replace( 'Wordpress', 'WordPress', $text );
4147 // Still here? Use the more judicious replacement
4148 static $dblq = false;
4149 if ( false === $dblq ) {
4150 $dblq = _x( '“', 'opening curly double quote' );
4153 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
4154 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
4159 * Sanitize a mime type
4163 * @param string $mime_type Mime type
4164 * @return string Sanitized mime type
4166 function sanitize_mime_type( $mime_type ) {
4167 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
4169 * Filter a mime type following sanitization.
4173 * @param string $sani_mime_type The sanitized mime type.
4174 * @param string $mime_type The mime type prior to sanitization.
4176 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
4180 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
4184 * @param string $to_ping Space or carriage return separated URLs
4185 * @return string URLs starting with the http or https protocol, separated by a carriage return.
4187 function sanitize_trackback_urls( $to_ping ) {
4188 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
4189 foreach ( $urls_to_ping as $k => $url ) {
4190 if ( !preg_match( '#^https?://.#i', $url ) )
4191 unset( $urls_to_ping[$k] );
4193 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
4194 $urls_to_ping = implode( "\n", $urls_to_ping );
4196 * Filter a list of trackback URLs following sanitization.
4198 * The string returned here consists of a space or carriage return-delimited list
4199 * of trackback URLs.
4203 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
4204 * @param string $to_ping Space or carriage return separated URLs before sanitization.
4206 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
4210 * Add slashes to a string or array of strings.
4212 * This should be used when preparing data for core API that expects slashed data.
4213 * This should not be used to escape data going directly into an SQL query.
4217 * @param string|array $value String or array of strings to slash.
4218 * @return string|array Slashed $value
4220 function wp_slash( $value ) {
4221 if ( is_array( $value ) ) {
4222 foreach ( $value as $k => $v ) {
4223 if ( is_array( $v ) ) {
4224 $value[$k] = wp_slash( $v );
4226 $value[$k] = addslashes( $v );
4230 $value = addslashes( $value );
4237 * Remove slashes from a string or array of strings.
4239 * This should be used to remove slashes from data passed to core API that
4240 * expects data to be unslashed.
4244 * @param string|array $value String or array of strings to unslash.
4245 * @return string|array Unslashed $value
4247 function wp_unslash( $value ) {
4248 return stripslashes_deep( $value );
4252 * Extract and return the first URL from passed content.
4256 * @param string $content A string which might contain a URL.
4257 * @return string|false The found URL.
4259 function get_url_in_content( $content ) {
4260 if ( empty( $content ) ) {
4264 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
4265 return esc_url_raw( $matches[2] );
4272 * Returns the regexp for common whitespace characters.
4274 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
4275 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
4276 * sequence was found to be unreliable due to random inclusion of the A0 byte.
4280 * @staticvar string $spaces
4282 * @return string The spaces regexp.
4284 function wp_spaces_regexp() {
4285 static $spaces = '';
4287 if ( empty( $spaces ) ) {
4289 * Filter the regexp for common whitespace characters.
4291 * This string is substituted for the \s sequence as needed in regular
4292 * expressions. For websites not written in English, different characters
4293 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
4294 * sequence may not be in use.
4298 * @param string $spaces Regexp pattern for matching common whitespace characters.
4300 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );
4307 * Print the important emoji-related styles.
4311 * @staticvar bool $printed
4313 function print_emoji_styles() {
4314 static $printed = false;
4322 <style type="text/css">
4325 display: inline !important;
4326 border: none !important;
4327 box-shadow: none !important;
4328 height: 1em !important;
4329 width: 1em !important;
4330 margin: 0 .07em !important;
4331 vertical-align: -0.1em !important;
4332 background: none !important;
4333 padding: 0 !important;
4341 * @global string $wp_version
4342 * @staticvar bool $printed
4344 function print_emoji_detection_script() {
4346 static $printed = false;
4356 * Filter the URL where emoji images are hosted.
4360 * @param string The emoji base URL.
4362 'baseUrl' => apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) ),
4365 * Filter the extension of the emoji files.
4369 * @param string The emoji extension. Default .png.
4371 'ext' => apply_filters( 'emoji_ext', '.png' ),
4374 $version = 'ver=' . $wp_version;
4376 if ( SCRIPT_DEBUG ) {
4377 $settings['source'] = array(
4378 /** This filter is documented in wp-includes/class.wp-scripts.php */
4379 'wpemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji.js?$version" ), 'wpemoji' ),
4380 /** This filter is documented in wp-includes/class.wp-scripts.php */
4381 'twemoji' => apply_filters( 'script_loader_src', includes_url( "js/twemoji.js?$version" ), 'twemoji' ),
4385 <script type="text/javascript">
4386 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4387 <?php readfile( ABSPATH . WPINC . "/js/wp-emoji-loader.js" ); ?>
4391 $settings['source'] = array(
4392 /** This filter is documented in wp-includes/class.wp-scripts.php */
4393 'concatemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji-release.min.js?$version" ), 'concatemoji' ),
4397 * If you're looking at a src version of this file, you'll see an "include"
4398 * statement below. This is used by the `grunt build` process to directly
4399 * include a minified version of wp-emoji-loader.js, instead of using the
4400 * readfile() method from above.
4402 * If you're looking at a build version of this file, you'll see a string of
4403 * minified JavaScript. If you need to debug it, please turn on SCRIPT_DEBUG
4404 * and edit wp-emoji-loader.js directly.
4407 <script type="text/javascript">
4408 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4409 !function(a,b,c){function d(a){var c=b.createElement("canvas"),d=c.getContext&&c.getContext("2d");return d&&d.fillText?(d.textBaseline="top",d.font="600 32px Arial","flag"===a?(d.fillText(String.fromCharCode(55356,56812,55356,56807),0,0),c.toDataURL().length>3e3):(d.fillText(String.fromCharCode(55357,56835),0,0),0!==d.getImageData(16,16,1,1).data[0])):!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;c.supports={simple:d("simple"),flag:d("flag")},c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.simple&&c.supports.flag||(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);
4416 * Convert any 4 byte emoji in a string to their equivalent HTML entity.
4418 * Currently, only Unicode 7 emoji are supported. Skin tone modifiers are allowed,
4419 * all other Unicode 8 emoji will be added when the spec is finalised.
4421 * This allows us to store emoji in a DB using the utf8 character set.
4425 * @param string $content The content to encode.
4426 * @return string The encoded content.
4428 function wp_encode_emoji( $content ) {
4429 if ( function_exists( 'mb_convert_encoding' ) ) {
4431 \x23\xE2\x83\xA3 # Digits
4432 [\x30-\x39]\xE2\x83\xA3
4433 | \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
4434 | \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
4435 | \xF0\x9F\x98[\x80-\xBF] # Smilies
4436 | \xF0\x9F\x99[\x80-\x8F]
4437 | \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
4441 if ( preg_match_all( $regex, $content, $matches ) ) {
4442 if ( ! empty( $matches[1] ) ) {
4443 foreach( $matches[1] as $emoji ) {
4445 * UTF-32's hex encoding is the same as HTML's hex encoding.
4446 * So, by converting the emoji from UTF-8 to UTF-32, we magically
4447 * get the correct hex encoding.
4449 $unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
4450 if ( isset( $unpacked[1] ) ) {
4451 $entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
4452 $content = str_replace( $emoji, $entity, $content );
4463 * Convert emoji to a static img element.
4467 * @param string $text The content to encode.
4468 * @return string The encoded content.
4470 function wp_staticize_emoji( $text ) {
4471 $text = wp_encode_emoji( $text );
4473 /** This filter is documented in wp-includes/formatting.php */
4474 $cdn_url = apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) );
4476 /** This filter is documented in wp-includes/formatting.php */
4477 $ext = apply_filters( 'emoji_ext', '.png' );
4481 * HTML loop taken from smiley function, which was taken from texturize function.
4482 * It'll never be consolidated.
4484 * First, capture the tags as well as in between.
4486 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
4487 $stop = count( $textarr );
4489 // Ignore processing of specific tags.
4490 $tags_to_ignore = 'code|pre|style|script|textarea';
4491 $ignore_block_element = '';
4493 for ( $i = 0; $i < $stop; $i++ ) {
4494 $content = $textarr[$i];
4496 // If we're in an ignore block, wait until we find its closing tag.
4497 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
4498 $ignore_block_element = $matches[1];
4501 // If it's not a tag and not in ignore block.
4502 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
4504 if ( preg_match_all( '/(DZ(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches ) ) {
4505 if ( ! empty( $matches[0] ) ) {
4506 foreach ( $matches[0] as $flag ) {
4507 $chars = str_replace( array( '&#x', ';'), '', $flag );
4509 list( $char1, $char2 ) = str_split( $chars, 5 );
4510 $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 ) );
4512 $content = str_replace( $flag, $entity, $content );
4517 // Loosely match the Emoji Unicode range.
4518 $regex = '/(&#x[2-3][0-9a-f]{3};|[1-6][0-9a-f]{2};)/';
4521 if ( preg_match_all( $regex, $content, $matches ) ) {
4522 if ( ! empty( $matches[1] ) ) {
4523 foreach ( $matches[1] as $emoji ) {
4524 $char = str_replace( array( '&#x', ';'), '', $emoji );
4525 $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode( $emoji ) );
4527 $content = str_replace( $emoji, $entity, $content );
4533 // Did we exit ignore block.
4534 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
4535 $ignore_block_element = '';
4538 $output .= $content;
4545 * Convert emoji in emails into static images.
4549 * @param array $mail The email data array.
4550 * @return array The email data array, with emoji in the message staticized.
4552 function wp_staticize_emoji_for_email( $mail ) {
4553 if ( ! isset( $mail['message'] ) ) {
4558 * We can only transform the emoji into images if it's a text/html email.
4559 * To do that, here's a cut down version of the same process that happens
4560 * in wp_mail() - get the Content-Type from the headers, if there is one,
4561 * then pass it through the wp_mail_content_type filter, in case a plugin
4562 * is handling changing the Content-Type.
4565 if ( isset( $mail['headers'] ) ) {
4566 if ( is_array( $mail['headers'] ) ) {
4567 $headers = $mail['headers'];
4569 $headers = explode( "\n", str_replace( "\r\n", "\n", $mail['headers'] ) );
4573 foreach ( $headers as $header ) {
4574 if ( strpos($header, ':') === false ) {
4578 // Explode them out.
4579 list( $name, $content ) = explode( ':', trim( $header ), 2 );
4582 $name = trim( $name );
4583 $content = trim( $content );
4585 if ( 'content-type' === strtolower( $name ) ) {
4586 if ( strpos( $content, ';' ) !== false ) {
4587 list( $type, $charset ) = explode( ';', $content );
4588 $content_type = trim( $type );
4590 $content_type = trim( $content );
4596 // Set Content-Type if we don't have a content-type from the input headers.
4597 if ( ! isset( $content_type ) ) {
4598 $content_type = 'text/plain';
4601 /** This filter is documented in wp-includes/pluggable.php */
4602 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
4604 if ( 'text/html' === $content_type ) {
4605 $mail['message'] = wp_staticize_emoji( $mail['message'] );