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 $pee = str_replace( " <!-- wpnl --> ", "\n", $pee );
605 * Separate HTML elements and comments from the text.
609 * @param string $input The text which has to be formatted.
610 * @return array The formatted text.
612 function wp_html_split( $input ) {
615 if ( ! isset( $regex ) ) {
617 '!' // Start of comment, after the <.
618 . '(?:' // Unroll the loop: Consume everything until --> is found.
619 . '-(?!->)' // Dash not followed by end of comment.
620 . '[^\-]*+' // Consume non-dashes.
621 . ')*+' // Loop possessively.
622 . '(?:-->)?'; // End of comment. If not found, match all input.
625 '!\[CDATA\[' // Start of comment, after the <.
626 . '[^\]]*+' // Consume non-].
627 . '(?:' // Unroll the loop: Consume everything until ]]> is found.
628 . '](?!]>)' // One ] not followed by end of comment.
629 . '[^\]]*+' // Consume non-].
630 . ')*+' // Loop possessively.
631 . '(?:]]>)?'; // End of comment. If not found, match all input.
634 '/(' // Capture the entire match.
635 . '<' // Find start of element.
636 . '(?(?=!--)' // Is this a comment?
637 . $comments // Find end of comment.
639 . '(?(?=!\[CDATA\[)' // Is this a comment?
640 . $cdata // Find end of comment.
642 . '[^>]*>?' // Find end of element. If not found, match all input.
648 return preg_split( $regex, $input, -1, PREG_SPLIT_DELIM_CAPTURE );
652 * Replace characters or phrases within HTML elements only.
656 * @param string $haystack The text which has to be formatted.
657 * @param array $replace_pairs In the form array('from' => 'to', ...).
658 * @return string The formatted text.
660 function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
661 // Find all elements.
662 $textarr = wp_html_split( $haystack );
665 // Optimize when searching for one item.
666 if ( 1 === count( $replace_pairs ) ) {
667 // Extract $needle and $replace.
668 foreach ( $replace_pairs as $needle => $replace );
670 // Loop through delimeters (elements) only.
671 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
672 if ( false !== strpos( $textarr[$i], $needle ) ) {
673 $textarr[$i] = str_replace( $needle, $replace, $textarr[$i] );
678 // Extract all $needles.
679 $needles = array_keys( $replace_pairs );
681 // Loop through delimeters (elements) only.
682 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
683 foreach ( $needles as $needle ) {
684 if ( false !== strpos( $textarr[$i], $needle ) ) {
685 $textarr[$i] = strtr( $textarr[$i], $replace_pairs );
687 // After one strtr() break out of the foreach loop and look at next element.
695 $haystack = implode( $textarr );
702 * Newline preservation help function for wpautop
707 * @param array $matches preg_replace_callback matches array
710 function _autop_newline_preservation_helper( $matches ) {
711 return str_replace( "\n", "<WPPreserveNewline />", $matches[0] );
715 * Don't auto-p wrap shortcodes that stand alone
717 * Ensures that shortcodes are not wrapped in `<p>...</p>`.
721 * @global array $shortcode_tags
723 * @param string $pee The content.
724 * @return string The filtered content.
726 function shortcode_unautop( $pee ) {
727 global $shortcode_tags;
729 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
733 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
734 $spaces = wp_spaces_regexp();
738 . '<p>' // Opening paragraph
739 . '(?:' . $spaces . ')*+' // Optional leading whitespace
740 . '(' // 1: The shortcode
741 . '\\[' // Opening bracket
742 . "($tagregexp)" // 2: Shortcode name
743 . '(?![\\w-])' // Not followed by word character or hyphen
744 // Unroll the loop: Inside the opening shortcode tag
745 . '[^\\]\\/]*' // Not a closing bracket or forward slash
747 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
748 . '[^\\]\\/]*' // Not a closing bracket or forward slash
751 . '\\/\\]' // Self closing tag and closing bracket
753 . '\\]' // Closing bracket
754 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
755 . '[^\\[]*+' // Not an opening bracket
757 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
758 . '[^\\[]*+' // Not an opening bracket
760 . '\\[\\/\\2\\]' // Closing shortcode tag
764 . '(?:' . $spaces . ')*+' // optional trailing whitespace
765 . '<\\/p>' // closing paragraph
768 return preg_replace( $pattern, '$1', $pee );
772 * Checks to see if a string is utf8 encoded.
774 * NOTE: This function checks for 5-Byte sequences, UTF8
775 * has Bytes Sequences with a maximum length of 4.
777 * @author bmorel at ssi dot fr (modified)
780 * @param string $str The string to be checked
781 * @return bool True if $str fits a UTF-8 model, false otherwise.
783 function seems_utf8( $str ) {
784 mbstring_binary_safe_encoding();
785 $length = strlen($str);
786 reset_mbstring_encoding();
787 for ($i=0; $i < $length; $i++) {
789 if ($c < 0x80) $n = 0; // 0bbbbbbb
790 elseif (($c & 0xE0) == 0xC0) $n=1; // 110bbbbb
791 elseif (($c & 0xF0) == 0xE0) $n=2; // 1110bbbb
792 elseif (($c & 0xF8) == 0xF0) $n=3; // 11110bbb
793 elseif (($c & 0xFC) == 0xF8) $n=4; // 111110bb
794 elseif (($c & 0xFE) == 0xFC) $n=5; // 1111110b
795 else return false; // Does not match any model
796 for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
797 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
805 * Converts a number of special characters into their HTML entities.
807 * Specifically deals with: &, <, >, ", and '.
809 * $quote_style can be set to ENT_COMPAT to encode " to
810 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
815 * @staticvar string $_charset
817 * @param string $string The text which is to be encoded.
818 * @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.
819 * @param string $charset Optional. The character encoding of the string. Default is false.
820 * @param bool $double_encode Optional. Whether to encode existing html entities. Default is false.
821 * @return string The encoded text with HTML entities.
823 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
824 $string = (string) $string;
826 if ( 0 === strlen( $string ) )
829 // Don't bother if there are no specialchars - saves some processing
830 if ( ! preg_match( '/[&<>"\']/', $string ) )
833 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
834 if ( empty( $quote_style ) )
835 $quote_style = ENT_NOQUOTES;
836 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
837 $quote_style = ENT_QUOTES;
839 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
841 static $_charset = null;
842 if ( ! isset( $_charset ) ) {
843 $alloptions = wp_load_alloptions();
844 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
846 $charset = $_charset;
849 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
852 $_quote_style = $quote_style;
854 if ( $quote_style === 'double' ) {
855 $quote_style = ENT_COMPAT;
856 $_quote_style = ENT_COMPAT;
857 } elseif ( $quote_style === 'single' ) {
858 $quote_style = ENT_NOQUOTES;
861 if ( ! $double_encode ) {
862 // Guarantee every &entity; is valid, convert &garbage; into &garbage;
863 // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
864 $string = wp_kses_normalize_entities( $string );
867 $string = @htmlspecialchars( $string, $quote_style, $charset, $double_encode );
869 // Backwards compatibility
870 if ( 'single' === $_quote_style )
871 $string = str_replace( "'", ''', $string );
877 * Converts a number of HTML entities into their special characters.
879 * Specifically deals with: &, <, >, ", and '.
881 * $quote_style can be set to ENT_COMPAT to decode " entities,
882 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
886 * @param string $string The text which is to be decoded.
887 * @param string|int $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
888 * both single and double if set to ENT_QUOTES or
889 * none if set to ENT_NOQUOTES.
890 * Also compatible with old _wp_specialchars() values;
891 * converting single quotes if set to 'single',
892 * double if set to 'double' or both if otherwise set.
893 * Default is ENT_NOQUOTES.
894 * @return string The decoded text without HTML entities.
896 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
897 $string = (string) $string;
899 if ( 0 === strlen( $string ) ) {
903 // Don't bother if there are no entities - saves a lot of processing
904 if ( strpos( $string, '&' ) === false ) {
908 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
909 if ( empty( $quote_style ) ) {
910 $quote_style = ENT_NOQUOTES;
911 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
912 $quote_style = ENT_QUOTES;
915 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
916 $single = array( ''' => '\'', ''' => '\'' );
917 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
918 $double = array( '"' => '"', '"' => '"', '"' => '"' );
919 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
920 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
921 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
923 if ( $quote_style === ENT_QUOTES ) {
924 $translation = array_merge( $single, $double, $others );
925 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
926 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
927 $translation = array_merge( $double, $others );
928 $translation_preg = array_merge( $double_preg, $others_preg );
929 } elseif ( $quote_style === 'single' ) {
930 $translation = array_merge( $single, $others );
931 $translation_preg = array_merge( $single_preg, $others_preg );
932 } elseif ( $quote_style === ENT_NOQUOTES ) {
933 $translation = $others;
934 $translation_preg = $others_preg;
937 // Remove zero padding on numeric entities
938 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
940 // Replace characters according to translation table
941 return strtr( $string, $translation );
945 * Checks for invalid UTF8 in a string.
949 * @staticvar bool $is_utf8
950 * @staticvar bool $utf8_pcre
952 * @param string $string The text which is to be checked.
953 * @param bool $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
954 * @return string The checked text.
956 function wp_check_invalid_utf8( $string, $strip = false ) {
957 $string = (string) $string;
959 if ( 0 === strlen( $string ) ) {
963 // Store the site charset as a static to avoid multiple calls to get_option()
964 static $is_utf8 = null;
965 if ( ! isset( $is_utf8 ) ) {
966 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
972 // Check for support for utf8 in the installed PCRE library once and store the result in a static
973 static $utf8_pcre = null;
974 if ( ! isset( $utf8_pcre ) ) {
975 $utf8_pcre = @preg_match( '/^./u', 'a' );
977 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
982 // preg_match fails when it encounters invalid UTF8 in $string
983 if ( 1 === @preg_match( '/^./us', $string ) ) {
987 // Attempt to strip the bad chars if requested (not recommended)
988 if ( $strip && function_exists( 'iconv' ) ) {
989 return iconv( 'utf-8', 'utf-8', $string );
996 * Encode the Unicode values to be used in the URI.
1000 * @param string $utf8_string
1001 * @param int $length Max length of the string
1002 * @return string String with Unicode encoded for URI.
1004 function utf8_uri_encode( $utf8_string, $length = 0 ) {
1008 $unicode_length = 0;
1010 mbstring_binary_safe_encoding();
1011 $string_length = strlen( $utf8_string );
1012 reset_mbstring_encoding();
1014 for ($i = 0; $i < $string_length; $i++ ) {
1016 $value = ord( $utf8_string[ $i ] );
1018 if ( $value < 128 ) {
1019 if ( $length && ( $unicode_length >= $length ) )
1021 $unicode .= chr($value);
1024 if ( count( $values ) == 0 ) {
1025 if ( $value < 224 ) {
1027 } elseif ( $value < 240 ) {
1036 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
1038 if ( count( $values ) == $num_octets ) {
1039 for ( $j = 0; $j < $num_octets; $j++ ) {
1040 $unicode .= '%' . dechex( $values[ $j ] );
1043 $unicode_length += $num_octets * 3;
1055 * Converts all accent characters to ASCII characters.
1057 * If there are no accent characters, then the string given is just returned.
1061 * @param string $string Text that might have accent characters
1062 * @return string Filtered string with replaced "nice" characters.
1064 function remove_accents( $string ) {
1065 if ( !preg_match('/[\x80-\xff]/', $string) )
1068 if (seems_utf8($string)) {
1070 // Decompositions for Latin-1 Supplement
1071 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
1072 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
1073 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
1074 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
1075 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
1076 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
1077 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
1078 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
1079 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
1080 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
1081 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
1082 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
1083 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
1084 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
1085 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
1086 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
1087 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
1088 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
1089 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
1090 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
1091 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
1092 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
1093 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
1094 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
1095 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
1096 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
1097 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
1098 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
1099 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
1100 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
1101 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
1102 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
1103 // Decompositions for Latin Extended-A
1104 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
1105 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
1106 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
1107 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
1108 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
1109 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
1110 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
1111 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
1112 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
1113 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
1114 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
1115 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
1116 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
1117 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
1118 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
1119 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
1120 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
1121 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
1122 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
1123 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
1124 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
1125 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
1126 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
1127 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
1128 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
1129 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
1130 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
1131 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
1132 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
1133 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
1134 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
1135 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
1136 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
1137 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
1138 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
1139 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
1140 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
1141 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
1142 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
1143 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
1144 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
1145 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
1146 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
1147 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
1148 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
1149 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
1150 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
1151 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
1152 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
1153 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
1154 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
1155 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
1156 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
1157 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
1158 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
1159 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
1160 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
1161 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
1162 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
1163 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
1164 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
1165 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
1166 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
1167 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
1168 // Decompositions for Latin Extended-B
1169 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
1170 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
1172 chr(226).chr(130).chr(172) => 'E',
1174 chr(194).chr(163) => '',
1175 // Vowels with diacritic (Vietnamese)
1177 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
1178 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
1180 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
1181 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
1182 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
1183 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
1184 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
1185 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
1186 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
1188 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
1189 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
1190 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
1191 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
1192 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
1193 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
1194 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
1195 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
1196 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
1197 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
1198 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
1199 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
1201 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
1202 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
1203 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
1204 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
1205 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
1206 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
1207 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
1208 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
1210 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
1211 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
1212 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
1213 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
1214 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
1215 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
1217 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
1218 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
1219 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
1220 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
1221 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
1222 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
1223 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
1224 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
1225 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
1226 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
1227 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
1228 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
1229 // Vowels with diacritic (Chinese, Hanyu Pinyin)
1230 chr(201).chr(145) => 'a',
1232 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
1234 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
1236 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
1237 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
1238 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
1239 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
1240 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
1242 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
1245 // Used for locale-specific rules
1246 $locale = get_locale();
1248 if ( 'de_DE' == $locale || 'de_DE_formal' == $locale ) {
1249 $chars[ chr(195).chr(132) ] = 'Ae';
1250 $chars[ chr(195).chr(164) ] = 'ae';
1251 $chars[ chr(195).chr(150) ] = 'Oe';
1252 $chars[ chr(195).chr(182) ] = 'oe';
1253 $chars[ chr(195).chr(156) ] = 'Ue';
1254 $chars[ chr(195).chr(188) ] = 'ue';
1255 $chars[ chr(195).chr(159) ] = 'ss';
1256 } elseif ( 'da_DK' === $locale ) {
1257 $chars[ chr(195).chr(134) ] = 'Ae';
1258 $chars[ chr(195).chr(166) ] = 'ae';
1259 $chars[ chr(195).chr(152) ] = 'Oe';
1260 $chars[ chr(195).chr(184) ] = 'oe';
1261 $chars[ chr(195).chr(133) ] = 'Aa';
1262 $chars[ chr(195).chr(165) ] = 'aa';
1265 $string = strtr($string, $chars);
1268 // Assume ISO-8859-1 if not UTF-8
1269 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1270 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1271 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1272 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1273 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1274 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1275 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1276 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1277 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1278 .chr(252).chr(253).chr(255);
1280 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1282 $string = strtr($string, $chars['in'], $chars['out']);
1283 $double_chars = array();
1284 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1285 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1286 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1293 * Sanitizes a filename, replacing whitespace with dashes.
1295 * Removes special characters that are illegal in filenames on certain
1296 * operating systems and special characters requiring special escaping
1297 * to manipulate at the command line. Replaces spaces and consecutive
1298 * dashes with a single dash. Trims period, dash and underscore from beginning
1299 * and end of filename.
1303 * @param string $filename The filename to be sanitized
1304 * @return string The sanitized filename
1306 function sanitize_file_name( $filename ) {
1307 $filename_raw = $filename;
1308 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1310 * Filter the list of characters to remove from a filename.
1314 * @param array $special_chars Characters to remove.
1315 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1317 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1318 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1319 $filename = str_replace( $special_chars, '', $filename );
1320 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1321 $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
1322 $filename = trim( $filename, '.-_' );
1324 // Split the filename into a base and extension[s]
1325 $parts = explode('.', $filename);
1327 // Return if only one extension
1328 if ( count( $parts ) <= 2 ) {
1330 * Filter a sanitized filename string.
1334 * @param string $filename Sanitized filename.
1335 * @param string $filename_raw The filename prior to sanitization.
1337 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1340 // Process multiple extensions
1341 $filename = array_shift($parts);
1342 $extension = array_pop($parts);
1343 $mimes = get_allowed_mime_types();
1346 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1347 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1349 foreach ( (array) $parts as $part) {
1350 $filename .= '.' . $part;
1352 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1354 foreach ( $mimes as $ext_preg => $mime_match ) {
1355 $ext_preg = '!^(' . $ext_preg . ')$!i';
1356 if ( preg_match( $ext_preg, $part ) ) {
1365 $filename .= '.' . $extension;
1366 /** This filter is documented in wp-includes/formatting.php */
1367 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1371 * Sanitizes a username, stripping out unsafe characters.
1373 * Removes tags, octets, entities, and if strict is enabled, will only keep
1374 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1375 * raw username (the username in the parameter), and the value of $strict as
1376 * parameters for the 'sanitize_user' filter.
1380 * @param string $username The username to be sanitized.
1381 * @param bool $strict If set limits $username to specific characters. Default false.
1382 * @return string The sanitized username, after passing through filters.
1384 function sanitize_user( $username, $strict = false ) {
1385 $raw_username = $username;
1386 $username = wp_strip_all_tags( $username );
1387 $username = remove_accents( $username );
1389 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1390 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1392 // If strict, reduce to ASCII for max portability.
1394 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1396 $username = trim( $username );
1397 // Consolidate contiguous whitespace
1398 $username = preg_replace( '|\s+|', ' ', $username );
1401 * Filter a sanitized username string.
1405 * @param string $username Sanitized username.
1406 * @param string $raw_username The username prior to sanitization.
1407 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1409 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1413 * Sanitizes a string key.
1415 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1419 * @param string $key String key
1420 * @return string Sanitized key
1422 function sanitize_key( $key ) {
1424 $key = strtolower( $key );
1425 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1428 * Filter a sanitized key string.
1432 * @param string $key Sanitized key.
1433 * @param string $raw_key The key prior to sanitization.
1435 return apply_filters( 'sanitize_key', $key, $raw_key );
1439 * Sanitizes a title, or returns a fallback title.
1441 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1442 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1447 * @param string $title The string to be sanitized.
1448 * @param string $fallback_title Optional. A title to use if $title is empty.
1449 * @param string $context Optional. The operation for which the string is sanitized
1450 * @return string The sanitized string.
1452 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1453 $raw_title = $title;
1455 if ( 'save' == $context )
1456 $title = remove_accents($title);
1459 * Filter a sanitized title string.
1463 * @param string $title Sanitized title.
1464 * @param string $raw_title The title prior to sanitization.
1465 * @param string $context The context for which the title is being sanitized.
1467 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1469 if ( '' === $title || false === $title )
1470 $title = $fallback_title;
1476 * Sanitizes a title with the 'query' context.
1478 * Used for querying the database for a value from URL.
1482 * @param string $title The string to be sanitized.
1483 * @return string The sanitized string.
1485 function sanitize_title_for_query( $title ) {
1486 return sanitize_title( $title, '', 'query' );
1490 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1492 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1493 * Whitespace becomes a dash.
1497 * @param string $title The title to be sanitized.
1498 * @param string $raw_title Optional. Not used.
1499 * @param string $context Optional. The operation for which the string is sanitized.
1500 * @return string The sanitized title.
1502 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1503 $title = strip_tags($title);
1504 // Preserve escaped octets.
1505 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1506 // Remove percent signs that are not part of an octet.
1507 $title = str_replace('%', '', $title);
1509 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1511 if (seems_utf8($title)) {
1512 if (function_exists('mb_strtolower')) {
1513 $title = mb_strtolower($title, 'UTF-8');
1515 $title = utf8_uri_encode($title, 200);
1518 $title = strtolower($title);
1519 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1520 $title = str_replace('.', '-', $title);
1522 if ( 'save' == $context ) {
1523 // Convert nbsp, ndash and mdash to hyphens
1524 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1526 // Strip these characters entirely
1527 $title = str_replace( array(
1531 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1533 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1534 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1535 // copy, reg, deg, hellip and trade
1536 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1538 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1539 // grave accent, macron, caron
1540 '%cc%80', '%cc%84', '%cc%8c',
1543 // Convert times to x
1544 $title = str_replace( '%c3%97', 'x', $title );
1547 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1548 $title = preg_replace('/\s+/', '-', $title);
1549 $title = preg_replace('|-+|', '-', $title);
1550 $title = trim($title, '-');
1556 * Ensures a string is a valid SQL 'order by' clause.
1558 * Accepts one or more columns, with or without a sort order (ASC / DESC).
1559 * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
1561 * Also accepts 'RAND()'.
1565 * @param string $orderby Order by clause to be validated.
1566 * @return string|false Returns $orderby if valid, false otherwise.
1568 function sanitize_sql_orderby( $orderby ) {
1569 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 ) ) {
1576 * Sanitizes an HTML classname to ensure it only contains valid characters.
1578 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1579 * string then it will return the alternative value supplied.
1581 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1585 * @param string $class The classname to be sanitized
1586 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1587 * Defaults to an empty string.
1588 * @return string The sanitized value
1590 function sanitize_html_class( $class, $fallback = '' ) {
1591 //Strip out any % encoded octets
1592 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1594 //Limit to A-Z,a-z,0-9,_,-
1595 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1597 if ( '' == $sanitized )
1598 $sanitized = $fallback;
1601 * Filter a sanitized HTML class string.
1605 * @param string $sanitized The sanitized HTML class.
1606 * @param string $class HTML class before sanitization.
1607 * @param string $fallback The fallback string.
1609 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1613 * Converts lone & characters into `&` (a.k.a. `&`)
1617 * @param string $content String of characters to be converted.
1618 * @param string $deprecated Not used.
1619 * @return string Converted string.
1621 function convert_chars( $content, $deprecated = '' ) {
1622 if ( ! empty( $deprecated ) ) {
1623 _deprecated_argument( __FUNCTION__, '0.71' );
1626 if ( strpos( $content, '&' ) !== false ) {
1627 $content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content );
1634 * Converts invalid Unicode references range to valid range.
1638 * @param string $content String with entities that need converting.
1639 * @return string Converted string.
1641 function convert_invalid_entities( $content ) {
1642 $wp_htmltranswinuni = array(
1643 '€' => '€', // the Euro sign
1645 '‚' => '‚', // these are Windows CP1252 specific characters
1646 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1647 '„' => '„',
1648 '…' => '…',
1649 '†' => '†',
1650 '‡' => '‡',
1651 'ˆ' => 'ˆ',
1652 '‰' => '‰',
1653 'Š' => 'Š',
1654 '‹' => '‹',
1655 'Œ' => 'Œ',
1657 'Ž' => 'Ž',
1660 '‘' => '‘',
1661 '’' => '’',
1662 '“' => '“',
1663 '”' => '”',
1664 '•' => '•',
1665 '–' => '–',
1666 '—' => '—',
1667 '˜' => '˜',
1668 '™' => '™',
1669 'š' => 'š',
1670 '›' => '›',
1671 'œ' => 'œ',
1673 'ž' => 'ž',
1674 'Ÿ' => 'Ÿ'
1677 if ( strpos( $content, '' ) !== false ) {
1678 $content = strtr( $content, $wp_htmltranswinuni );
1685 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1689 * @param string $text Text to be balanced
1690 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1691 * @return string Balanced text
1693 function balanceTags( $text, $force = false ) {
1694 if ( $force || get_option('use_balanceTags') == 1 ) {
1695 return force_balance_tags( $text );
1702 * Balances tags of string using a modified stack.
1706 * @author Leonard Lin <leonard@acm.org>
1708 * @copyright November 4, 2001
1710 * @todo Make better - change loop condition to $text in 1.2
1711 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1712 * 1.1 Fixed handling of append/stack pop order of end text
1713 * Added Cleaning Hooks
1716 * @param string $text Text to be balanced.
1717 * @return string Balanced text.
1719 function force_balance_tags( $text ) {
1720 $tagstack = array();
1724 // Known single-entity/self-closing tags
1725 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1726 // Tags that can be immediately nested within themselves
1727 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1729 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1730 $text = str_replace('< !--', '< !--', $text);
1731 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1732 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1734 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1735 $newtext .= $tagqueue;
1737 $i = strpos($text, $regex[0]);
1738 $l = strlen($regex[0]);
1740 // clear the shifter
1743 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1744 $tag = strtolower(substr($regex[1],1));
1745 // if too many closing tags
1746 if ( $stacksize <= 0 ) {
1748 // or close to be safe $tag = '/' . $tag;
1750 // if stacktop value = tag close value then pop
1751 elseif ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1752 $tag = '</' . $tag . '>'; // Close Tag
1754 array_pop( $tagstack );
1756 } else { // closing tag not at top, search for it
1757 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1758 if ( $tagstack[$j] == $tag ) {
1759 // add tag to tagqueue
1760 for ( $k = $stacksize-1; $k >= $j; $k--) {
1761 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1769 } else { // Begin Tag
1770 $tag = strtolower($regex[1]);
1774 // If it's an empty tag "< >", do nothing
1778 // ElseIf it presents itself as a self-closing tag...
1779 elseif ( substr( $regex[2], -1 ) == '/' ) {
1780 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1781 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1782 if ( ! in_array( $tag, $single_tags ) )
1783 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1785 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1786 elseif ( in_array($tag, $single_tags) ) {
1789 // Else it's not a single-entity tag
1791 // If the top of the stack is the same as the tag we want to push, close previous tag
1792 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1793 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1796 $stacksize = array_push( $tagstack, $tag );
1800 $attributes = $regex[2];
1801 if ( ! empty( $attributes ) && $attributes[0] != '>' )
1802 $attributes = ' ' . $attributes;
1804 $tag = '<' . $tag . $attributes . '>';
1805 //If already queuing a close tag, then put this tag on, too
1806 if ( !empty($tagqueue) ) {
1811 $newtext .= substr($text, 0, $i) . $tag;
1812 $text = substr($text, $i + $l);
1816 $newtext .= $tagqueue;
1818 // Add Remaining text
1822 while( $x = array_pop($tagstack) )
1823 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1825 // WP fix for the bug with HTML comments
1826 $newtext = str_replace("< !--","<!--",$newtext);
1827 $newtext = str_replace("< !--","< !--",$newtext);
1833 * Acts on text which is about to be edited.
1835 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1836 * to convert special characters to HTML entities. If $richedit is set to true,
1837 * it is simply a holder for the 'format_to_edit' filter.
1841 * @param string $content The text about to be edited.
1842 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1843 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1845 function format_to_edit( $content, $richedit = false ) {
1847 * Filter the text to be formatted for editing.
1851 * @param string $content The text, prior to formatting for editing.
1853 $content = apply_filters( 'format_to_edit', $content );
1855 $content = esc_textarea( $content );
1860 * Add leading zeros when necessary.
1862 * If you set the threshold to '4' and the number is '10', then you will get
1863 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1864 * will get back '5000'.
1866 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1867 * and the size of the number. If the number is large enough, then no zeros will
1872 * @param int $number Number to append zeros to if not greater than threshold.
1873 * @param int $threshold Digit places number needs to be to not have zeros added.
1874 * @return string Adds leading zeros to number if needed.
1876 function zeroise( $number, $threshold ) {
1877 return sprintf( '%0' . $threshold . 's', $number );
1881 * Adds backslashes before letters and before a number at the start of a string.
1885 * @param string $string Value to which backslashes will be added.
1886 * @return string String with backslashes inserted.
1888 function backslashit( $string ) {
1889 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1890 $string = '\\\\' . $string;
1891 return addcslashes( $string, 'A..Za..z' );
1895 * Appends a trailing slash.
1897 * Will remove trailing forward and backslashes if it exists already before adding
1898 * a trailing forward slash. This prevents double slashing a string or path.
1900 * The primary use of this is for paths and thus should be used for paths. It is
1901 * not restricted to paths and offers no specific path support.
1905 * @param string $string What to add the trailing slash to.
1906 * @return string String with trailing slash added.
1908 function trailingslashit( $string ) {
1909 return untrailingslashit( $string ) . '/';
1913 * Removes trailing forward slashes and backslashes if they exist.
1915 * The primary use of this is for paths and thus should be used for paths. It is
1916 * not restricted to paths and offers no specific path support.
1920 * @param string $string What to remove the trailing slashes from.
1921 * @return string String without the trailing slashes.
1923 function untrailingslashit( $string ) {
1924 return rtrim( $string, '/\\' );
1928 * Adds slashes to escape strings.
1930 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1931 * http://www.php.net/magic_quotes} for more details.
1935 * @param string $gpc The string returned from HTTP request data.
1936 * @return string Returns a string escaped with slashes.
1938 function addslashes_gpc($gpc) {
1939 if ( get_magic_quotes_gpc() )
1940 $gpc = stripslashes($gpc);
1942 return wp_slash($gpc);
1946 * Navigates through an array and removes slashes from the values.
1948 * If an array is passed, the array_map() function causes a callback to pass the
1949 * value back to the function. The slashes from this value will removed.
1953 * @param mixed $value The value to be stripped.
1954 * @return mixed Stripped value.
1956 function stripslashes_deep( $value ) {
1957 if ( is_array($value) ) {
1958 $value = array_map('stripslashes_deep', $value);
1959 } elseif ( is_object($value) ) {
1960 $vars = get_object_vars( $value );
1961 foreach ($vars as $key=>$data) {
1962 $value->{$key} = stripslashes_deep( $data );
1964 } elseif ( is_string( $value ) ) {
1965 $value = stripslashes($value);
1972 * Navigates through an array and encodes the values to be used in a URL.
1977 * @param array|string $value The array or string to be encoded.
1978 * @return array|string $value The encoded array (or string from the callback).
1980 function urlencode_deep( $value ) {
1981 return is_array( $value ) ? array_map( 'urlencode_deep', $value ) : urlencode( $value );
1985 * Navigates through an array and raw encodes the values to be used in a URL.
1989 * @param array|string $value The array or string to be encoded.
1990 * @return array|string $value The encoded array (or string from the callback).
1992 function rawurlencode_deep( $value ) {
1993 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1997 * Converts email addresses characters to HTML entities to block spam bots.
2001 * @param string $email_address Email address.
2002 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
2003 * @return string Converted email address.
2005 function antispambot( $email_address, $hex_encoding = 0 ) {
2006 $email_no_spam_address = '';
2007 for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
2008 $j = rand( 0, 1 + $hex_encoding );
2010 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
2011 } elseif ( $j == 1 ) {
2012 $email_no_spam_address .= $email_address[$i];
2013 } elseif ( $j == 2 ) {
2014 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
2018 return str_replace( '@', '@', $email_no_spam_address );
2022 * Callback to convert URI match to HTML A element.
2024 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2025 * make_clickable()}.
2030 * @param array $matches Single Regex Match.
2031 * @return string HTML A element with URI address.
2033 function _make_url_clickable_cb( $matches ) {
2036 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
2037 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
2038 // Then we can let the parenthesis balancer do its thing below.
2039 $url .= $matches[3];
2042 $suffix = $matches[3];
2045 // Include parentheses in the URL only if paired
2046 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
2047 $suffix = strrchr( $url, ')' ) . $suffix;
2048 $url = substr( $url, 0, strrpos( $url, ')' ) );
2051 $url = esc_url($url);
2055 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
2059 * Callback to convert URL match to HTML A element.
2061 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2062 * make_clickable()}.
2067 * @param array $matches Single Regex Match.
2068 * @return string HTML A element with URL address.
2070 function _make_web_ftp_clickable_cb( $matches ) {
2072 $dest = $matches[2];
2073 $dest = 'http://' . $dest;
2074 $dest = esc_url($dest);
2078 // removed trailing [.,;:)] from URL
2079 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
2080 $ret = substr($dest, -1);
2081 $dest = substr($dest, 0, strlen($dest)-1);
2083 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
2087 * Callback to convert email address match to HTML A element.
2089 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2090 * make_clickable()}.
2095 * @param array $matches Single Regex Match.
2096 * @return string HTML A element with email address.
2098 function _make_email_clickable_cb( $matches ) {
2099 $email = $matches[2] . '@' . $matches[3];
2100 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
2104 * Convert plaintext URI to HTML links.
2106 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
2111 * @param string $text Content to convert URIs.
2112 * @return string Content with converted URIs.
2114 function make_clickable( $text ) {
2116 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
2117 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
2118 foreach ( $textarr as $piece ) {
2120 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
2122 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
2125 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
2130 // Long strings might contain expensive edge cases ...
2131 if ( 10000 < strlen( $piece ) ) {
2133 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
2134 if ( 2101 < strlen( $chunk ) ) {
2135 $r .= $chunk; // Too big, no whitespace: bail.
2137 $r .= make_clickable( $chunk );
2141 $ret = " $piece "; // Pad with whitespace to simplify the regexes
2144 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
2146 [\\w]{1,20}+:// # Scheme and hier-part prefix
2147 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
2148 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
2149 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
2150 [\'.,;:!?)] # Punctuation URL character
2151 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
2154 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
2155 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
2156 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
2158 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
2160 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
2161 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
2163 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
2168 // Cleanup of accidental links within links
2169 return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
2173 * Breaks a string into chunks by splitting at whitespace characters.
2174 * The length of each returned chunk is as close to the specified length goal as possible,
2175 * with the caveat that each chunk includes its trailing delimiter.
2176 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
2178 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
2180 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
2182 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
2184 * 0 => '1234 67890 ', // 11 characters: Perfect split
2185 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
2186 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
2187 * 3 => '1234 890 ', // 11 characters: Perfect split
2188 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
2189 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
2190 * 6 => ' 45678 ', // 11 characters: Perfect split
2191 * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
2197 * @param string $string The string to split.
2198 * @param int $goal The desired chunk length.
2199 * @return array Numeric array of chunks.
2201 function _split_str_by_whitespace( $string, $goal ) {
2204 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
2206 while ( $goal < strlen( $string_nullspace ) ) {
2207 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
2209 if ( false === $pos ) {
2210 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
2211 if ( false === $pos ) {
2216 $chunks[] = substr( $string, 0, $pos + 1 );
2217 $string = substr( $string, $pos + 1 );
2218 $string_nullspace = substr( $string_nullspace, $pos + 1 );
2222 $chunks[] = $string;
2229 * Adds rel nofollow string to all HTML A elements in content.
2233 * @param string $text Content that may contain HTML A elements.
2234 * @return string Converted content.
2236 function wp_rel_nofollow( $text ) {
2237 // This is a pre save filter, so text is already escaped.
2238 $text = stripslashes($text);
2239 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
2240 return wp_slash( $text );
2244 * Callback to add rel=nofollow string to HTML A element.
2246 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2247 * string to prevent from invalidating (X)HTML.
2251 * @param array $matches Single Match
2252 * @return string HTML A Element with rel nofollow.
2254 function wp_rel_nofollow_callback( $matches ) {
2255 $text = $matches[1];
2256 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
2257 return "<a $text rel=\"nofollow\">";
2261 * Convert one smiley code to the icon graphic file equivalent.
2263 * Callback handler for {@link convert_smilies()}.
2264 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2265 * `<img>` string for that smiley.
2269 * @global array $wpsmiliestrans
2271 * @param array $matches Single match. Smiley code to convert to image.
2272 * @return string Image string for smiley.
2274 function translate_smiley( $matches ) {
2275 global $wpsmiliestrans;
2277 if ( count( $matches ) == 0 )
2280 $smiley = trim( reset( $matches ) );
2281 $img = $wpsmiliestrans[ $smiley ];
2284 $ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
2285 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
2287 // Don't convert smilies that aren't images - they're probably emoji.
2288 if ( ! in_array( $ext, $image_exts ) ) {
2293 * Filter the Smiley image URL before it's used in the image element.
2297 * @param string $smiley_url URL for the smiley image.
2298 * @param string $img Filename for the smiley image.
2299 * @param string $site_url Site URL, as returned by site_url().
2301 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2303 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
2307 * Convert text equivalent of smilies to images.
2309 * Will only convert smilies if the option 'use_smilies' is true and the global
2310 * used in the function isn't empty.
2314 * @global string|array $wp_smiliessearch
2316 * @param string $text Content to convert smilies from text.
2317 * @return string Converted content with text smilies replaced with images.
2319 function convert_smilies( $text ) {
2320 global $wp_smiliessearch;
2322 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2323 // HTML loop taken from texturize function, could possible be consolidated
2324 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2325 $stop = count( $textarr );// loop stuff
2327 // Ignore proessing of specific tags
2328 $tags_to_ignore = 'code|pre|style|script|textarea';
2329 $ignore_block_element = '';
2331 for ( $i = 0; $i < $stop; $i++ ) {
2332 $content = $textarr[$i];
2334 // If we're in an ignore block, wait until we find its closing tag
2335 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2336 $ignore_block_element = $matches[1];
2339 // If it's not a tag and not in ignore block
2340 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2341 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2344 // did we exit ignore block
2345 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2346 $ignore_block_element = '';
2349 $output .= $content;
2352 // return default text.
2359 * Verifies that an email is valid.
2361 * Does not grok i18n domains. Not RFC compliant.
2365 * @param string $email Email address to verify.
2366 * @param bool $deprecated Deprecated.
2367 * @return string|bool Either false or the valid email address.
2369 function is_email( $email, $deprecated = false ) {
2370 if ( ! empty( $deprecated ) )
2371 _deprecated_argument( __FUNCTION__, '3.0' );
2373 // Test for the minimum length the email can be
2374 if ( strlen( $email ) < 3 ) {
2376 * Filter whether an email address is valid.
2378 * This filter is evaluated under several different contexts, such as 'email_too_short',
2379 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2380 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2384 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2385 * @param string $email The email address being checked.
2386 * @param string $message An explanatory message to the user.
2387 * @param string $context Context under which the email was tested.
2389 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2392 // Test for an @ character after the first position
2393 if ( strpos( $email, '@', 1 ) === false ) {
2394 /** This filter is documented in wp-includes/formatting.php */
2395 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2398 // Split out the local and domain parts
2399 list( $local, $domain ) = explode( '@', $email, 2 );
2402 // Test for invalid characters
2403 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2404 /** This filter is documented in wp-includes/formatting.php */
2405 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2409 // Test for sequences of periods
2410 if ( preg_match( '/\.{2,}/', $domain ) ) {
2411 /** This filter is documented in wp-includes/formatting.php */
2412 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2415 // Test for leading and trailing periods and whitespace
2416 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2417 /** This filter is documented in wp-includes/formatting.php */
2418 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2421 // Split the domain into subs
2422 $subs = explode( '.', $domain );
2424 // Assume the domain will have at least two subs
2425 if ( 2 > count( $subs ) ) {
2426 /** This filter is documented in wp-includes/formatting.php */
2427 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2430 // Loop through each sub
2431 foreach ( $subs as $sub ) {
2432 // Test for leading and trailing hyphens and whitespace
2433 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2434 /** This filter is documented in wp-includes/formatting.php */
2435 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2438 // Test for invalid characters
2439 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2440 /** This filter is documented in wp-includes/formatting.php */
2441 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2445 // Congratulations your email made it!
2446 /** This filter is documented in wp-includes/formatting.php */
2447 return apply_filters( 'is_email', $email, $email, null );
2451 * Convert to ASCII from email subjects.
2455 * @param string $string Subject line
2456 * @return string Converted string to ASCII
2458 function wp_iso_descrambler( $string ) {
2459 /* this may only work with iso-8859-1, I'm afraid */
2460 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2463 $subject = str_replace('_', ' ', $matches[2]);
2464 return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
2469 * Helper function to convert hex encoded chars to ASCII
2474 * @param array $match The preg_replace_callback matches array
2475 * @return string Converted chars
2477 function _wp_iso_convert( $match ) {
2478 return chr( hexdec( strtolower( $match[1] ) ) );
2482 * Returns a date in the GMT equivalent.
2484 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2485 * timezone_string available, the date is assumed to be in that timezone,
2486 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2487 * format can be overridden using the $format parameter.
2491 * @param string $string The date to be converted.
2492 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2493 * @return string GMT version of the date provided.
2495 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2496 $tz = get_option( 'timezone_string' );
2498 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2500 return gmdate( $format, 0 );
2501 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2502 $string_gmt = $datetime->format( $format );
2504 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 ) )
2505 return gmdate( $format, 0 );
2506 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2507 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2513 * Converts a GMT date into the correct format for the blog.
2515 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2516 * timezone_string available, the returned date is in that timezone, otherwise
2517 * it simply adds the value of gmt_offset. Return format can be overridden
2518 * using the $format parameter
2522 * @param string $string The date to be converted.
2523 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2524 * @return string Formatted date relative to the timezone / GMT offset.
2526 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2527 $tz = get_option( 'timezone_string' );
2529 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2531 return date( $format, 0 );
2532 $datetime->setTimezone( new DateTimeZone( $tz ) );
2533 $string_localtime = $datetime->format( $format );
2535 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) )
2536 return date( $format, 0 );
2537 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2538 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2540 return $string_localtime;
2544 * Computes an offset in seconds from an iso8601 timezone.
2548 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2549 * @return int|float The offset in seconds.
2551 function iso8601_timezone_to_offset( $timezone ) {
2552 // $timezone is either 'Z' or '[+|-]hhmm'
2553 if ($timezone == 'Z') {
2556 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2557 $hours = intval(substr($timezone, 1, 2));
2558 $minutes = intval(substr($timezone, 3, 4)) / 60;
2559 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2565 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2569 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2570 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2571 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2573 function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
2574 $timezone = strtolower($timezone);
2576 if ($timezone == 'gmt') {
2578 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);
2580 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2581 $offset = iso8601_timezone_to_offset($date_bits[7]);
2582 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2583 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2586 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2587 $timestamp -= $offset;
2589 return gmdate('Y-m-d H:i:s', $timestamp);
2591 } elseif ($timezone == 'user') {
2592 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);
2597 * Adds a element attributes to open links in new windows.
2599 * Comment text in popup windows should be filtered through this. Right now it's
2600 * a moderately dumb function, ideally it would detect whether a target or rel
2601 * attribute was already there and adjust its actions accordingly.
2605 * @param string $text Content to replace links to open in a new window.
2606 * @return string Content that has filtered links.
2608 function popuplinks( $text ) {
2609 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2614 * Strips out all characters that are not allowable in an email.
2618 * @param string $email Email address to filter.
2619 * @return string Filtered email address.
2621 function sanitize_email( $email ) {
2622 // Test for the minimum length the email can be
2623 if ( strlen( $email ) < 3 ) {
2625 * Filter a sanitized email address.
2627 * This filter is evaluated under several contexts, including 'email_too_short',
2628 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2629 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2633 * @param string $email The sanitized email address.
2634 * @param string $email The email address, as provided to sanitize_email().
2635 * @param string $message A message to pass to the user.
2637 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2640 // Test for an @ character after the first position
2641 if ( strpos( $email, '@', 1 ) === false ) {
2642 /** This filter is documented in wp-includes/formatting.php */
2643 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2646 // Split out the local and domain parts
2647 list( $local, $domain ) = explode( '@', $email, 2 );
2650 // Test for invalid characters
2651 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2652 if ( '' === $local ) {
2653 /** This filter is documented in wp-includes/formatting.php */
2654 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2658 // Test for sequences of periods
2659 $domain = preg_replace( '/\.{2,}/', '', $domain );
2660 if ( '' === $domain ) {
2661 /** This filter is documented in wp-includes/formatting.php */
2662 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2665 // Test for leading and trailing periods and whitespace
2666 $domain = trim( $domain, " \t\n\r\0\x0B." );
2667 if ( '' === $domain ) {
2668 /** This filter is documented in wp-includes/formatting.php */
2669 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2672 // Split the domain into subs
2673 $subs = explode( '.', $domain );
2675 // Assume the domain will have at least two subs
2676 if ( 2 > count( $subs ) ) {
2677 /** This filter is documented in wp-includes/formatting.php */
2678 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2681 // Create an array that will contain valid subs
2682 $new_subs = array();
2684 // Loop through each sub
2685 foreach ( $subs as $sub ) {
2686 // Test for leading and trailing hyphens
2687 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2689 // Test for invalid characters
2690 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2692 // If there's anything left, add it to the valid subs
2693 if ( '' !== $sub ) {
2698 // If there aren't 2 or more valid subs
2699 if ( 2 > count( $new_subs ) ) {
2700 /** This filter is documented in wp-includes/formatting.php */
2701 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2704 // Join valid subs into the new domain
2705 $domain = join( '.', $new_subs );
2707 // Put the email back together
2708 $email = $local . '@' . $domain;
2710 // Congratulations your email made it!
2711 /** This filter is documented in wp-includes/formatting.php */
2712 return apply_filters( 'sanitize_email', $email, $email, null );
2716 * Determines the difference between two timestamps.
2718 * The difference is returned in a human readable format such as "1 hour",
2719 * "5 mins", "2 days".
2723 * @param int $from Unix timestamp from which the difference begins.
2724 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2725 * @return string Human readable time difference.
2727 function human_time_diff( $from, $to = '' ) {
2728 if ( empty( $to ) ) {
2732 $diff = (int) abs( $to - $from );
2734 if ( $diff < HOUR_IN_SECONDS ) {
2735 $mins = round( $diff / MINUTE_IN_SECONDS );
2738 /* translators: min=minute */
2739 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2740 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2741 $hours = round( $diff / HOUR_IN_SECONDS );
2744 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2745 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2746 $days = round( $diff / DAY_IN_SECONDS );
2749 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2750 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2751 $weeks = round( $diff / WEEK_IN_SECONDS );
2754 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2755 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2756 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2759 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2760 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2761 $years = round( $diff / YEAR_IN_SECONDS );
2764 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2768 * Filter the human readable difference between two timestamps.
2772 * @param string $since The difference in human readable text.
2773 * @param int $diff The difference in seconds.
2774 * @param int $from Unix timestamp from which the difference begins.
2775 * @param int $to Unix timestamp to end the time difference.
2777 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2781 * Generates an excerpt from the content, if needed.
2783 * The excerpt word amount will be 55 words and if the amount is greater than
2784 * that, then the string ' […]' will be appended to the excerpt. If the string
2785 * is less than 55 words, then the content will be returned as is.
2787 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2788 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2792 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2793 * @return string The excerpt.
2795 function wp_trim_excerpt( $text = '' ) {
2796 $raw_excerpt = $text;
2797 if ( '' == $text ) {
2798 $text = get_the_content('');
2800 $text = strip_shortcodes( $text );
2802 /** This filter is documented in wp-includes/post-template.php */
2803 $text = apply_filters( 'the_content', $text );
2804 $text = str_replace(']]>', ']]>', $text);
2807 * Filter the number of words in an excerpt.
2811 * @param int $number The number of words. Default 55.
2813 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2815 * Filter the string in the "more" link displayed after a trimmed excerpt.
2819 * @param string $more_string The string shown within the more link.
2821 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2822 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2825 * Filter the trimmed excerpt string.
2829 * @param string $text The trimmed text.
2830 * @param string $raw_excerpt The text prior to trimming.
2832 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2836 * Trims text to a certain number of words.
2838 * This function is localized. For languages that count 'words' by the individual
2839 * character (such as East Asian languages), the $num_words argument will apply
2840 * to the number of individual characters.
2844 * @param string $text Text to trim.
2845 * @param int $num_words Number of words. Default 55.
2846 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2847 * @return string Trimmed text.
2849 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2850 if ( null === $more ) {
2851 $more = __( '…' );
2854 $original_text = $text;
2855 $text = wp_strip_all_tags( $text );
2858 * translators: If your word count is based on single characters (e.g. East Asian characters),
2859 * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
2860 * Do not translate into your own language.
2862 if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2863 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2864 preg_match_all( '/./u', $text, $words_array );
2865 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2868 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2872 if ( count( $words_array ) > $num_words ) {
2873 array_pop( $words_array );
2874 $text = implode( $sep, $words_array );
2875 $text = $text . $more;
2877 $text = implode( $sep, $words_array );
2881 * Filter the text content after words have been trimmed.
2885 * @param string $text The trimmed text.
2886 * @param int $num_words The number of words to trim the text to. Default 5.
2887 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2888 * @param string $original_text The text before it was trimmed.
2890 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2894 * Converts named entities into numbered entities.
2898 * @param string $text The text within which entities will be converted.
2899 * @return string Text with converted entities.
2901 function ent2ncr( $text ) {
2904 * Filter text before named entities are converted into numbered entities.
2906 * A non-null string must be returned for the filter to be evaluated.
2910 * @param null $converted_text The text to be converted. Default null.
2911 * @param string $text The text prior to entity conversion.
2913 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2914 if ( null !== $filtered )
2918 '"' => '"',
2923 ' ' => ' ',
2924 '¡' => '¡',
2925 '¢' => '¢',
2926 '£' => '£',
2927 '¤' => '¤',
2928 '¥' => '¥',
2929 '¦' => '¦',
2930 '&brkbar;' => '¦',
2931 '§' => '§',
2932 '¨' => '¨',
2933 '¨' => '¨',
2934 '©' => '©',
2935 'ª' => 'ª',
2936 '«' => '«',
2937 '¬' => '¬',
2938 '­' => '­',
2939 '®' => '®',
2940 '¯' => '¯',
2941 '&hibar;' => '¯',
2942 '°' => '°',
2943 '±' => '±',
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 'Λ' => 'Λ',
3044 'Ο' => 'Ο',
3046 'Ρ' => 'Ρ',
3047 'Σ' => 'Σ',
3048 'Τ' => 'Τ',
3049 'Υ' => 'Υ',
3050 'Φ' => 'Φ',
3051 'Χ' => 'Χ',
3052 'Ψ' => 'Ψ',
3053 'Ω' => 'Ω',
3054 'α' => 'α',
3055 'β' => 'β',
3056 'γ' => 'γ',
3057 'δ' => 'δ',
3058 'ε' => 'ε',
3059 'ζ' => 'ζ',
3060 'η' => 'η',
3061 'θ' => 'θ',
3062 'ι' => 'ι',
3063 'κ' => 'κ',
3064 'λ' => 'λ',
3068 'ο' => 'ο',
3070 'ρ' => 'ρ',
3071 'ς' => 'ς',
3072 'σ' => 'σ',
3073 'τ' => 'τ',
3074 'υ' => 'υ',
3075 'φ' => 'φ',
3076 'χ' => 'χ',
3077 'ψ' => 'ψ',
3078 'ω' => 'ω',
3079 'ϑ' => 'ϑ',
3080 'ϒ' => 'ϒ',
3081 'ϖ' => 'ϖ',
3082 ' ' => ' ',
3083 ' ' => ' ',
3084 ' ' => ' ',
3085 '‌' => '‌',
3086 '‍' => '‍',
3087 '‎' => '‎',
3088 '‏' => '‏',
3089 '–' => '–',
3090 '—' => '—',
3091 '‘' => '‘',
3092 '’' => '’',
3093 '‚' => '‚',
3094 '“' => '“',
3095 '”' => '”',
3096 '„' => '„',
3097 '†' => '†',
3098 '‡' => '‡',
3099 '•' => '•',
3100 '…' => '…',
3101 '‰' => '‰',
3102 '′' => '′',
3103 '″' => '″',
3104 '‹' => '‹',
3105 '›' => '›',
3106 '‾' => '‾',
3107 '⁄' => '⁄',
3108 '€' => '€',
3109 'ℑ' => 'ℑ',
3110 '℘' => '℘',
3111 'ℜ' => 'ℜ',
3112 '™' => '™',
3113 'ℵ' => 'ℵ',
3114 '↵' => '↵',
3115 '⇐' => '⇐',
3116 '⇑' => '⇑',
3117 '⇒' => '⇒',
3118 '⇓' => '⇓',
3119 '⇔' => '⇔',
3120 '∀' => '∀',
3121 '∂' => '∂',
3122 '∃' => '∃',
3123 '∅' => '∅',
3124 '∇' => '∇',
3125 '∈' => '∈',
3126 '∉' => '∉',
3127 '∋' => '∋',
3128 '∏' => '∏',
3129 '∑' => '∑',
3130 '−' => '−',
3131 '∗' => '∗',
3132 '√' => '√',
3133 '∝' => '∝',
3134 '∞' => '∞',
3135 '∠' => '∠',
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 '♦' => '♦'
3176 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
3180 * Formats text for the editor.
3182 * Generally the browsers treat everything inside a textarea as text, but
3183 * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
3185 * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
3186 * filter will be applied to an empty string.
3190 * @param string $text The text to be formatted.
3191 * @return string The formatted text after filter is applied.
3193 function format_for_editor( $text, $default_editor = null ) {
3195 $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
3199 * Filter the text after it is formatted for the editor.
3203 * @param string $text The formatted text.
3205 return apply_filters( 'format_for_editor', $text, $default_editor );
3209 * Perform a deep string replace operation to ensure the values in $search are no longer present
3211 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
3212 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
3213 * str_replace would return
3218 * @param string|array $search The value being searched for, otherwise known as the needle.
3219 * An array may be used to designate multiple needles.
3220 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
3221 * @return string The string with the replaced svalues.
3223 function _deep_replace( $search, $subject ) {
3224 $subject = (string) $subject;
3228 $subject = str_replace( $search, '', $subject, $count );
3235 * Escapes data for use in a MySQL query.
3237 * Usually you should prepare queries using wpdb::prepare().
3238 * Sometimes, spot-escaping is required or useful. One example
3239 * is preparing an array for use in an IN clause.
3243 * @global wpdb $wpdb
3245 * @param string|array $data Unescaped data
3246 * @return string|array Escaped data
3248 function esc_sql( $data ) {
3250 return $wpdb->_escape( $data );
3254 * Checks and cleans a URL.
3256 * A number of characters are removed from the URL. If the URL is for displaying
3257 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3258 * is applied to the returned cleaned URL.
3262 * @param string $url The URL to be cleaned.
3263 * @param array $protocols Optional. An array of acceptable protocols.
3264 * Defaults to return value of wp_allowed_protocols()
3265 * @param string $_context Private. Use esc_url_raw() for database usage.
3266 * @return string The cleaned $url after the 'clean_url' filter is applied.
3268 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3269 $original_url = $url;
3273 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3274 if ( 0 !== stripos( $url, 'mailto:' ) ) {
3275 $strip = array('%0d', '%0a', '%0D', '%0A');
3276 $url = _deep_replace($strip, $url);
3278 $url = str_replace(';//', '://', $url);
3279 /* If the URL doesn't appear to contain a scheme, we
3280 * presume it needs http:// appended (unless a relative
3281 * link starting with /, # or ? or a php file).
3283 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3284 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3285 $url = 'http://' . $url;
3287 // Replace ampersands and single quotes only when displaying.
3288 if ( 'display' == $_context ) {
3289 $url = wp_kses_normalize_entities( $url );
3290 $url = str_replace( '&', '&', $url );
3291 $url = str_replace( "'", ''', $url );
3294 if ( '/' === $url[0] ) {
3295 $good_protocol_url = $url;
3297 if ( ! is_array( $protocols ) )
3298 $protocols = wp_allowed_protocols();
3299 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3300 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3305 * Filter a string cleaned and escaped for output as a URL.
3309 * @param string $good_protocol_url The cleaned URL to be returned.
3310 * @param string $original_url The URL prior to cleaning.
3311 * @param string $_context If 'display', replace ampersands and single quotes only.
3313 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3317 * Performs esc_url() for database usage.
3321 * @param string $url The URL to be cleaned.
3322 * @param array $protocols An array of acceptable protocols.
3323 * @return string The cleaned URL.
3325 function esc_url_raw( $url, $protocols = null ) {
3326 return esc_url( $url, $protocols, 'db' );
3330 * Convert entities, while preserving already-encoded entities.
3332 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3336 * @param string $myHTML The text to be converted.
3337 * @return string Converted text.
3339 function htmlentities2( $myHTML ) {
3340 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3341 $translation_table[chr(38)] = '&';
3342 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3346 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3348 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3349 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3350 * be in single quotes. The filter 'js_escape' is also applied here.
3354 * @param string $text The text to be escaped.
3355 * @return string Escaped text.
3357 function esc_js( $text ) {
3358 $safe_text = wp_check_invalid_utf8( $text );
3359 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3360 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3361 $safe_text = str_replace( "\r", '', $safe_text );
3362 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3364 * Filter a string cleaned and escaped for output in JavaScript.
3366 * Text passed to esc_js() is stripped of invalid or special characters,
3367 * and properly slashed for output.
3371 * @param string $safe_text The text after it has been escaped.
3372 * @param string $text The text prior to being escaped.
3374 return apply_filters( 'js_escape', $safe_text, $text );
3378 * Escaping for HTML blocks.
3382 * @param string $text
3385 function esc_html( $text ) {
3386 $safe_text = wp_check_invalid_utf8( $text );
3387 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3389 * Filter a string cleaned and escaped for output in HTML.
3391 * Text passed to esc_html() is stripped of invalid or special characters
3396 * @param string $safe_text The text after it has been escaped.
3397 * @param string $text The text prior to being escaped.
3399 return apply_filters( 'esc_html', $safe_text, $text );
3403 * Escaping for HTML attributes.
3407 * @param string $text
3410 function esc_attr( $text ) {
3411 $safe_text = wp_check_invalid_utf8( $text );
3412 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3414 * Filter a string cleaned and escaped for output in an HTML attribute.
3416 * Text passed to esc_attr() is stripped of invalid or special characters
3421 * @param string $safe_text The text after it has been escaped.
3422 * @param string $text The text prior to being escaped.
3424 return apply_filters( 'attribute_escape', $safe_text, $text );
3428 * Escaping for textarea values.
3432 * @param string $text
3435 function esc_textarea( $text ) {
3436 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3438 * Filter a string cleaned and escaped for output in a textarea element.
3442 * @param string $safe_text The text after it has been escaped.
3443 * @param string $text The text prior to being escaped.
3445 return apply_filters( 'esc_textarea', $safe_text, $text );
3449 * Escape an HTML tag name.
3453 * @param string $tag_name
3456 function tag_escape( $tag_name ) {
3457 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3459 * Filter a string cleaned and escaped for output as an HTML tag.
3463 * @param string $safe_tag The tag name after it has been escaped.
3464 * @param string $tag_name The text before it was escaped.
3466 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3470 * Convert full URL paths to absolute paths.
3472 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3473 * beginning, so it isn't a true relative link, but from the web root base.
3476 * @since 4.1.0 Support was added for relative URLs.
3478 * @param string $link Full URL path.
3479 * @return string Absolute path.
3481 function wp_make_link_relative( $link ) {
3482 return preg_replace( '|^(https?:)?//[^/]+(/.*)|i', '$2', $link );
3486 * Sanitises various option values based on the nature of the option.
3488 * This is basically a switch statement which will pass $value through a number
3489 * of functions depending on the $option.
3493 * @global wpdb $wpdb
3495 * @param string $option The name of the option.
3496 * @param string $value The unsanitised value.
3497 * @return string Sanitized value.
3499 function sanitize_option( $option, $value ) {
3502 $original_value = $value;
3505 switch ( $option ) {
3506 case 'admin_email' :
3507 case 'new_admin_email' :
3508 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3509 if ( is_wp_error( $value ) ) {
3510 $error = $value->get_error_message();
3512 $value = sanitize_email( $value );
3513 if ( ! is_email( $value ) ) {
3514 $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
3519 case 'thumbnail_size_w':
3520 case 'thumbnail_size_h':
3521 case 'medium_size_w':
3522 case 'medium_size_h':
3523 case 'large_size_w':
3524 case 'large_size_h':
3525 case 'mailserver_port':
3526 case 'comment_max_links':
3527 case 'page_on_front':
3528 case 'page_for_posts':
3529 case 'rss_excerpt_length':
3530 case 'default_category':
3531 case 'default_email_category':
3532 case 'default_link_category':
3533 case 'close_comments_days_old':
3534 case 'comments_per_page':
3535 case 'thread_comments_depth':
3536 case 'users_can_register':
3537 case 'start_of_week':
3539 $value = absint( $value );
3542 case 'posts_per_page':
3543 case 'posts_per_rss':
3544 $value = (int) $value;
3545 if ( empty($value) )
3548 $value = abs($value);
3551 case 'default_ping_status':
3552 case 'default_comment_status':
3553 // Options that if not there have 0 value but need to be something like "closed"
3554 if ( $value == '0' || $value == '')
3558 case 'blogdescription':
3560 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3561 if ( is_wp_error( $value ) ) {
3562 $error = $value->get_error_message();
3564 $value = wp_kses_post( $value );
3565 $value = esc_html( $value );
3569 case 'blog_charset':
3570 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3574 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3575 if ( null === $value )
3578 $value = intval( $value );
3583 case 'mailserver_url':
3584 case 'mailserver_login':
3585 case 'mailserver_pass':
3587 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3588 if ( is_wp_error( $value ) ) {
3589 $error = $value->get_error_message();
3591 $value = strip_tags( $value );
3592 $value = wp_kses_data( $value );
3597 $value = explode( "\n", $value );
3598 $value = array_filter( array_map( 'trim', $value ) );
3599 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3600 $value = implode( "\n", $value );
3604 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3608 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3609 if ( is_wp_error( $value ) ) {
3610 $error = $value->get_error_message();
3612 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3613 $value = esc_url_raw( $value );
3615 $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3621 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3622 if ( is_wp_error( $value ) ) {
3623 $error = $value->get_error_message();
3625 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3626 $value = esc_url_raw( $value );
3628 $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3634 $allowed = get_available_languages();
3635 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3636 $allowed[] = WPLANG;
3638 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3639 $value = get_option( $option );
3643 case 'illegal_names':
3644 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3645 if ( is_wp_error( $value ) ) {
3646 $error = $value->get_error_message();
3648 if ( ! is_array( $value ) )
3649 $value = explode( ' ', $value );
3651 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3658 case 'limited_email_domains':
3659 case 'banned_email_domains':
3660 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3661 if ( is_wp_error( $value ) ) {
3662 $error = $value->get_error_message();
3664 if ( ! is_array( $value ) )
3665 $value = explode( "\n", $value );
3667 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3670 foreach ( $domains as $domain ) {
3671 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
3680 case 'timezone_string':
3681 $allowed_zones = timezone_identifiers_list();
3682 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3683 $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
3687 case 'permalink_structure':
3688 case 'category_base':
3690 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3691 if ( is_wp_error( $value ) ) {
3692 $error = $value->get_error_message();
3694 $value = esc_url_raw( $value );
3695 $value = str_replace( 'http://', '', $value );
3699 case 'default_role' :
3700 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3701 $value = 'subscriber';
3704 case 'moderation_keys':
3705 case 'blacklist_keys':
3706 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3707 if ( is_wp_error( $value ) ) {
3708 $error = $value->get_error_message();
3710 $value = explode( "\n", $value );
3711 $value = array_filter( array_map( 'trim', $value ) );
3712 $value = array_unique( $value );
3713 $value = implode( "\n", $value );
3718 if ( ! empty( $error ) ) {
3719 $value = get_option( $option );
3720 if ( function_exists( 'add_settings_error' ) ) {
3721 add_settings_error( $option, "invalid_{$option}", $error );
3726 * Filter an option value following sanitization.
3729 * @since 4.3.0 Added the `$original_value` parameter.
3731 * @param string $value The sanitized option value.
3732 * @param string $option The option name.
3733 * @param string $original_value The original value passed to the function.
3735 return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
3739 * Parses a string into variables to be stored in an array.
3741 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3742 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3746 * @param string $string The string to be parsed.
3747 * @param array $array Variables will be stored in this array.
3749 function wp_parse_str( $string, &$array ) {
3750 parse_str( $string, $array );
3751 if ( get_magic_quotes_gpc() )
3752 $array = stripslashes_deep( $array );
3754 * Filter the array of variables derived from a parsed string.
3758 * @param array $array The array populated with variables.
3760 $array = apply_filters( 'wp_parse_str', $array );
3764 * Convert lone less than signs.
3766 * KSES already converts lone greater than signs.
3770 * @param string $text Text to be converted.
3771 * @return string Converted text.
3773 function wp_pre_kses_less_than( $text ) {
3774 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3778 * Callback function used by preg_replace.
3782 * @param array $matches Populated by matches to preg_replace.
3783 * @return string The text returned after esc_html if needed.
3785 function wp_pre_kses_less_than_callback( $matches ) {
3786 if ( false === strpos($matches[0], '>') )
3787 return esc_html($matches[0]);
3792 * WordPress implementation of PHP sprintf() with filters.
3795 * @link http://www.php.net/sprintf
3797 * @param string $pattern The string which formatted args are inserted.
3798 * @param mixed $args ,... Arguments to be formatted into the $pattern string.
3799 * @return string The formatted string.
3801 function wp_sprintf( $pattern ) {
3802 $args = func_get_args();
3803 $len = strlen($pattern);
3807 while ( $len > $start ) {
3808 // Last character: append and break
3809 if ( strlen($pattern) - 1 == $start ) {
3810 $result .= substr($pattern, -1);
3814 // Literal %: append and continue
3815 if ( substr($pattern, $start, 2) == '%%' ) {
3821 // Get fragment before next %
3822 $end = strpos($pattern, '%', $start + 1);
3823 if ( false === $end )
3825 $fragment = substr($pattern, $start, $end - $start);
3827 // Fragment has a specifier
3828 if ( $pattern[$start] == '%' ) {
3829 // Find numbered arguments or take the next one in order
3830 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3831 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3832 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3835 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3839 * Filter a fragment from the pattern passed to wp_sprintf().
3841 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3845 * @param string $fragment A fragment from the pattern.
3846 * @param string $arg The argument.
3848 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3849 if ( $_fragment != $fragment )
3850 $fragment = $_fragment;
3852 $fragment = sprintf($fragment, strval($arg) );
3855 // Append to result and move to next fragment
3856 $result .= $fragment;
3863 * Localize list items before the rest of the content.
3865 * The '%l' must be at the first characters can then contain the rest of the
3866 * content. The list items will have ', ', ', and', and ' and ' added depending
3867 * on the amount of list items in the $args parameter.
3871 * @param string $pattern Content containing '%l' at the beginning.
3872 * @param array $args List items to prepend to the content and replace '%l'.
3873 * @return string Localized list items and rest of the content.
3875 function wp_sprintf_l( $pattern, $args ) {
3877 if ( substr($pattern, 0, 2) != '%l' )
3880 // Nothing to work with
3885 * Filter the translated delimiters used by wp_sprintf_l().
3886 * Placeholders (%s) are included to assist translators and then
3887 * removed before the array of strings reaches the filter.
3889 * Please note: Ampersands and entities should be avoided here.
3893 * @param array $delimiters An array of translated delimiters.
3895 $l = apply_filters( 'wp_sprintf_l', array(
3896 /* translators: used to join items in a list with more than 2 items */
3897 'between' => sprintf( __('%s, %s'), '', '' ),
3898 /* translators: used to join last two items in a list with more than 2 times */
3899 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3900 /* translators: used to join items in a list with only 2 items */
3901 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3904 $args = (array) $args;
3905 $result = array_shift($args);
3906 if ( count($args) == 1 )
3907 $result .= $l['between_only_two'] . array_shift($args);
3908 // Loop when more than two args
3911 $arg = array_shift($args);
3914 $result .= $l['between_last_two'] . $arg;
3916 $result .= $l['between'] . $arg;
3918 return $result . substr($pattern, 2);
3922 * Safely extracts not more than the first $count characters from html string.
3924 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3925 * be counted as one character. For example & will be counted as 4, < as
3930 * @param string $str String to get the excerpt from.
3931 * @param int $count Maximum number of characters to take.
3932 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3933 * @return string The excerpt.
3935 function wp_html_excerpt( $str, $count, $more = null ) {
3936 if ( null === $more )
3938 $str = wp_strip_all_tags( $str, true );
3939 $excerpt = mb_substr( $str, 0, $count );
3940 // remove part of an entity at the end
3941 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3942 if ( $str != $excerpt )
3943 $excerpt = trim( $excerpt ) . $more;
3948 * Add a Base url to relative links in passed content.
3950 * By default it supports the 'src' and 'href' attributes. However this can be
3951 * changed via the 3rd param.
3955 * @global string $_links_add_base
3957 * @param string $content String to search for links in.
3958 * @param string $base The base URL to prefix to links.
3959 * @param array $attrs The attributes which should be processed.
3960 * @return string The processed content.
3962 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3963 global $_links_add_base;
3964 $_links_add_base = $base;
3965 $attrs = implode('|', (array)$attrs);
3966 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3970 * Callback to add a base url to relative links in passed content.
3975 * @global string $_links_add_base
3977 * @param string $m The matched link.
3978 * @return string The processed link.
3980 function _links_add_base( $m ) {
3981 global $_links_add_base;
3982 //1 = attribute name 2 = quotation mark 3 = URL
3983 return $m[1] . '=' . $m[2] .
3984 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3986 WP_HTTP::make_absolute_url( $m[3], $_links_add_base )
3992 * Adds a Target attribute to all links in passed content.
3994 * This function by default only applies to `<a>` tags, however this can be
3995 * modified by the 3rd param.
3997 * *NOTE:* Any current target attributed will be stripped and replaced.
4001 * @global string $_links_add_target
4003 * @param string $content String to search for links in.
4004 * @param string $target The Target to add to the links.
4005 * @param array $tags An array of tags to apply to.
4006 * @return string The processed content.
4008 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
4009 global $_links_add_target;
4010 $_links_add_target = $target;
4011 $tags = implode('|', (array)$tags);
4012 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
4016 * Callback to add a target attribute to all links in passed content.
4021 * @global string $_links_add_target
4023 * @param string $m The matched link.
4024 * @return string The processed link.
4026 function _links_add_target( $m ) {
4027 global $_links_add_target;
4029 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
4030 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
4034 * Normalize EOL characters and strip duplicate whitespace.
4038 * @param string $str The string to normalize.
4039 * @return string The normalized string.
4041 function normalize_whitespace( $str ) {
4042 $str = trim( $str );
4043 $str = str_replace( "\r", "\n", $str );
4044 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
4049 * Properly strip all HTML tags including script and style
4051 * This differs from strip_tags() because it removes the contents of
4052 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
4053 * will return 'something'. wp_strip_all_tags will return ''
4057 * @param string $string String containing HTML tags
4058 * @param bool $remove_breaks Optional. Whether to remove left over line breaks and white space chars
4059 * @return string The processed string.
4061 function wp_strip_all_tags($string, $remove_breaks = false) {
4062 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
4063 $string = strip_tags($string);
4065 if ( $remove_breaks )
4066 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
4068 return trim( $string );
4072 * Sanitize a string from user input or from the db
4074 * check for invalid UTF-8,
4075 * Convert single < characters to entity,
4077 * remove line breaks, tabs and extra white space,
4082 * @param string $str
4085 function sanitize_text_field( $str ) {
4086 $filtered = wp_check_invalid_utf8( $str );
4088 if ( strpos($filtered, '<') !== false ) {
4089 $filtered = wp_pre_kses_less_than( $filtered );
4090 // This will strip extra whitespace for us.
4091 $filtered = wp_strip_all_tags( $filtered, true );
4093 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
4097 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
4098 $filtered = str_replace($match[0], '', $filtered);
4103 // Strip out the whitespace that may now exist after removing the octets.
4104 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
4108 * Filter a sanitized text field string.
4112 * @param string $filtered The sanitized string.
4113 * @param string $str The string prior to being sanitized.
4115 return apply_filters( 'sanitize_text_field', $filtered, $str );
4119 * i18n friendly version of basename()
4123 * @param string $path A path.
4124 * @param string $suffix If the filename ends in suffix this will also be cut off.
4127 function wp_basename( $path, $suffix = '' ) {
4128 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
4132 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
4134 * Violating our coding standards for a good function name.
4138 * @staticvar string|false $dblq
4140 function capital_P_dangit( $text ) {
4141 // Simple replacement for titles
4142 $current_filter = current_filter();
4143 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
4144 return str_replace( 'Wordpress', 'WordPress', $text );
4145 // Still here? Use the more judicious replacement
4146 static $dblq = false;
4147 if ( false === $dblq ) {
4148 $dblq = _x( '“', 'opening curly double quote' );
4151 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
4152 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
4157 * Sanitize a mime type
4161 * @param string $mime_type Mime type
4162 * @return string Sanitized mime type
4164 function sanitize_mime_type( $mime_type ) {
4165 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
4167 * Filter a mime type following sanitization.
4171 * @param string $sani_mime_type The sanitized mime type.
4172 * @param string $mime_type The mime type prior to sanitization.
4174 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
4178 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
4182 * @param string $to_ping Space or carriage return separated URLs
4183 * @return string URLs starting with the http or https protocol, separated by a carriage return.
4185 function sanitize_trackback_urls( $to_ping ) {
4186 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
4187 foreach ( $urls_to_ping as $k => $url ) {
4188 if ( !preg_match( '#^https?://.#i', $url ) )
4189 unset( $urls_to_ping[$k] );
4191 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
4192 $urls_to_ping = implode( "\n", $urls_to_ping );
4194 * Filter a list of trackback URLs following sanitization.
4196 * The string returned here consists of a space or carriage return-delimited list
4197 * of trackback URLs.
4201 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
4202 * @param string $to_ping Space or carriage return separated URLs before sanitization.
4204 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
4208 * Add slashes to a string or array of strings.
4210 * This should be used when preparing data for core API that expects slashed data.
4211 * This should not be used to escape data going directly into an SQL query.
4215 * @param string|array $value String or array of strings to slash.
4216 * @return string|array Slashed $value
4218 function wp_slash( $value ) {
4219 if ( is_array( $value ) ) {
4220 foreach ( $value as $k => $v ) {
4221 if ( is_array( $v ) ) {
4222 $value[$k] = wp_slash( $v );
4224 $value[$k] = addslashes( $v );
4228 $value = addslashes( $value );
4235 * Remove slashes from a string or array of strings.
4237 * This should be used to remove slashes from data passed to core API that
4238 * expects data to be unslashed.
4242 * @param string|array $value String or array of strings to unslash.
4243 * @return string|array Unslashed $value
4245 function wp_unslash( $value ) {
4246 return stripslashes_deep( $value );
4250 * Extract and return the first URL from passed content.
4254 * @param string $content A string which might contain a URL.
4255 * @return string|false The found URL.
4257 function get_url_in_content( $content ) {
4258 if ( empty( $content ) ) {
4262 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
4263 return esc_url_raw( $matches[2] );
4270 * Returns the regexp for common whitespace characters.
4272 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
4273 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
4274 * sequence was found to be unreliable due to random inclusion of the A0 byte.
4278 * @staticvar string $spaces
4280 * @return string The spaces regexp.
4282 function wp_spaces_regexp() {
4283 static $spaces = '';
4285 if ( empty( $spaces ) ) {
4287 * Filter the regexp for common whitespace characters.
4289 * This string is substituted for the \s sequence as needed in regular
4290 * expressions. For websites not written in English, different characters
4291 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
4292 * sequence may not be in use.
4296 * @param string $spaces Regexp pattern for matching common whitespace characters.
4298 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );
4305 * Print the important emoji-related styles.
4309 * @staticvar bool $printed
4311 function print_emoji_styles() {
4312 static $printed = false;
4320 <style type="text/css">
4323 display: inline !important;
4324 border: none !important;
4325 box-shadow: none !important;
4326 height: 1em !important;
4327 width: 1em !important;
4328 margin: 0 .07em !important;
4329 vertical-align: -0.1em !important;
4330 background: none !important;
4331 padding: 0 !important;
4339 * @global string $wp_version
4340 * @staticvar bool $printed
4342 function print_emoji_detection_script() {
4344 static $printed = false;
4354 * Filter the URL where emoji images are hosted.
4358 * @param string The emoji base URL.
4360 'baseUrl' => apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) ),
4363 * Filter the extension of the emoji files.
4367 * @param string The emoji extension. Default .png.
4369 'ext' => apply_filters( 'emoji_ext', '.png' ),
4372 $version = 'ver=' . $wp_version;
4374 if ( SCRIPT_DEBUG ) {
4375 $settings['source'] = array(
4376 /** This filter is documented in wp-includes/class.wp-scripts.php */
4377 'wpemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji.js?$version" ), 'wpemoji' ),
4378 /** This filter is documented in wp-includes/class.wp-scripts.php */
4379 'twemoji' => apply_filters( 'script_loader_src', includes_url( "js/twemoji.js?$version" ), 'twemoji' ),
4383 <script type="text/javascript">
4384 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4385 <?php readfile( ABSPATH . WPINC . "/js/wp-emoji-loader.js" ); ?>
4389 $settings['source'] = array(
4390 /** This filter is documented in wp-includes/class.wp-scripts.php */
4391 'concatemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji-release.min.js?$version" ), 'concatemoji' ),
4395 * If you're looking at a src version of this file, you'll see an "include"
4396 * statement below. This is used by the `grunt build` process to directly
4397 * include a minified version of wp-emoji-loader.js, instead of using the
4398 * readfile() method from above.
4400 * If you're looking at a build version of this file, you'll see a string of
4401 * minified JavaScript. If you need to debug it, please turn on SCRIPT_DEBUG
4402 * and edit wp-emoji-loader.js directly.
4405 <script type="text/javascript">
4406 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4407 !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);
4414 * Convert any 4 byte emoji in a string to their equivalent HTML entity.
4416 * Currently, only Unicode 7 emoji are supported. Skin tone modifiers are allowed,
4417 * all other Unicode 8 emoji will be added when the spec is finalised.
4419 * This allows us to store emoji in a DB using the utf8 character set.
4423 * @param string $content The content to encode.
4424 * @return string The encoded content.
4426 function wp_encode_emoji( $content ) {
4427 if ( function_exists( 'mb_convert_encoding' ) ) {
4429 \x23\xE2\x83\xA3 # Digits
4430 [\x30-\x39]\xE2\x83\xA3
4431 | \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
4432 | \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
4433 | \xF0\x9F\x98[\x80-\xBF] # Smilies
4434 | \xF0\x9F\x99[\x80-\x8F]
4435 | \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
4439 if ( preg_match_all( $regex, $content, $matches ) ) {
4440 if ( ! empty( $matches[1] ) ) {
4441 foreach( $matches[1] as $emoji ) {
4443 * UTF-32's hex encoding is the same as HTML's hex encoding.
4444 * So, by converting the emoji from UTF-8 to UTF-32, we magically
4445 * get the correct hex encoding.
4447 $unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
4448 if ( isset( $unpacked[1] ) ) {
4449 $entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
4450 $content = str_replace( $emoji, $entity, $content );
4461 * Convert emoji to a static img element.
4465 * @param string $text The content to encode.
4466 * @return string The encoded content.
4468 function wp_staticize_emoji( $text ) {
4469 $text = wp_encode_emoji( $text );
4471 /** This filter is documented in wp-includes/formatting.php */
4472 $cdn_url = apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) );
4474 /** This filter is documented in wp-includes/formatting.php */
4475 $ext = apply_filters( 'emoji_ext', '.png' );
4479 * HTML loop taken from smiley function, which was taken from texturize function.
4480 * It'll never be consolidated.
4482 * First, capture the tags as well as in between.
4484 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
4485 $stop = count( $textarr );
4487 // Ignore processing of specific tags.
4488 $tags_to_ignore = 'code|pre|style|script|textarea';
4489 $ignore_block_element = '';
4491 for ( $i = 0; $i < $stop; $i++ ) {
4492 $content = $textarr[$i];
4494 // If we're in an ignore block, wait until we find its closing tag.
4495 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
4496 $ignore_block_element = $matches[1];
4499 // If it's not a tag and not in ignore block.
4500 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
4502 if ( preg_match_all( '/(DZ(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches ) ) {
4503 if ( ! empty( $matches[0] ) ) {
4504 foreach ( $matches[0] as $flag ) {
4505 $chars = str_replace( array( '&#x', ';'), '', $flag );
4507 list( $char1, $char2 ) = str_split( $chars, 5 );
4508 $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 ) );
4510 $content = str_replace( $flag, $entity, $content );
4515 // Loosely match the Emoji Unicode range.
4516 $regex = '/(&#x[2-3][0-9a-f]{3};|[1-6][0-9a-f]{2};)/';
4519 if ( preg_match_all( $regex, $content, $matches ) ) {
4520 if ( ! empty( $matches[1] ) ) {
4521 foreach ( $matches[1] as $emoji ) {
4522 $char = str_replace( array( '&#x', ';'), '', $emoji );
4523 $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode( $emoji ) );
4525 $content = str_replace( $emoji, $entity, $content );
4531 // Did we exit ignore block.
4532 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
4533 $ignore_block_element = '';
4536 $output .= $content;
4543 * Convert emoji in emails into static images.
4547 * @param array $mail The email data array.
4548 * @return array The email data array, with emoji in the message staticized.
4550 function wp_staticize_emoji_for_email( $mail ) {
4551 if ( ! isset( $mail['message'] ) ) {
4556 * We can only transform the emoji into images if it's a text/html email.
4557 * To do that, here's a cut down version of the same process that happens
4558 * in wp_mail() - get the Content-Type from the headers, if there is one,
4559 * then pass it through the wp_mail_content_type filter, in case a plugin
4560 * is handling changing the Content-Type.
4563 if ( isset( $mail['headers'] ) ) {
4564 if ( is_array( $mail['headers'] ) ) {
4565 $headers = $mail['headers'];
4567 $headers = explode( "\n", str_replace( "\r\n", "\n", $mail['headers'] ) );
4571 foreach ( $headers as $header ) {
4572 if ( strpos($header, ':') === false ) {
4576 // Explode them out.
4577 list( $name, $content ) = explode( ':', trim( $header ), 2 );
4580 $name = trim( $name );
4581 $content = trim( $content );
4583 if ( 'content-type' === strtolower( $name ) ) {
4584 if ( strpos( $content, ';' ) !== false ) {
4585 list( $type, $charset ) = explode( ';', $content );
4586 $content_type = trim( $type );
4588 $content_type = trim( $content );
4594 // Set Content-Type if we don't have a content-type from the input headers.
4595 if ( ! isset( $content_type ) ) {
4596 $content_type = 'text/plain';
4599 /** This filter is documented in wp-includes/pluggable.php */
4600 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
4602 if ( 'text/html' === $content_type ) {
4603 $mail['message'] = wp_staticize_emoji( $mail['message'] );