3 * Main WordPress Formatting API.
5 * Handles many functions for formatting output.
11 * Replaces common plain text characters into formatted entities
15 * 'cause today's effort makes it worth tomorrow's "holiday" ...
19 * ’cause today’s effort makes it worth tomorrow’s “holiday” …
21 * Code within certain html blocks are skipped.
24 * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
26 * @param string $text The text to be formatted
27 * @param bool $reset Set to true for unit testing. Translated patterns will reset.
28 * @return string The string replaced with html entities
30 function wptexturize($text, $reset = false) {
31 global $wp_cockneyreplace, $shortcode_tags;
32 static $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
33 $default_no_texturize_tags, $default_no_texturize_shortcodes, $run_texturize = true;
35 // If there's nothing to do, just stop.
36 if ( empty( $text ) || false === $run_texturize ) {
40 // Set up static variables. Run once only.
41 if ( $reset || ! isset( $static_characters ) ) {
43 * Filter whether to skip running wptexturize().
45 * Passing false to the filter will effectively short-circuit wptexturize().
46 * returning the original text passed to the function instead.
48 * The filter runs only once, the first time wptexturize() is called.
54 * @param bool $run_texturize Whether to short-circuit wptexturize().
56 $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
57 if ( false === $run_texturize ) {
61 /* translators: opening curly double quote */
62 $opening_quote = _x( '“', 'opening curly double quote' );
63 /* translators: closing curly double quote */
64 $closing_quote = _x( '”', 'closing curly double quote' );
66 /* translators: apostrophe, for example in 'cause or can't */
67 $apos = _x( '’', 'apostrophe' );
69 /* translators: prime, for example in 9' (nine feet) */
70 $prime = _x( '′', 'prime' );
71 /* translators: double prime, for example in 9" (nine inches) */
72 $double_prime = _x( '″', 'double prime' );
74 /* translators: opening curly single quote */
75 $opening_single_quote = _x( '‘', 'opening curly single quote' );
76 /* translators: closing curly single quote */
77 $closing_single_quote = _x( '’', 'closing curly single quote' );
79 /* translators: en dash */
80 $en_dash = _x( '–', 'en dash' );
81 /* translators: em dash */
82 $em_dash = _x( '—', 'em dash' );
84 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
85 $default_no_texturize_shortcodes = array('code');
87 // if a plugin has provided an autocorrect array, use it
88 if ( isset($wp_cockneyreplace) ) {
89 $cockney = array_keys($wp_cockneyreplace);
90 $cockneyreplace = array_values($wp_cockneyreplace);
91 } elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
92 $cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
93 $cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
95 $cockney = $cockneyreplace = array();
98 $static_characters = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
99 $static_replacements = array_merge( array( '…', $opening_quote, $closing_quote, ' ™' ), $cockneyreplace );
102 // Pattern-based replacements of characters.
103 // Sort the remaining patterns into several arrays for performance tuning.
104 $dynamic_characters = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
105 $dynamic_replacements = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
107 $spaces = wp_spaces_regexp();
109 // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
110 if ( "'" !== $apos || "'" !== $closing_single_quote ) {
111 $dynamic[ '/\'(\d\d)\'(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $apos . '$1' . $closing_single_quote;
113 if ( "'" !== $apos || '"' !== $closing_quote ) {
114 $dynamic[ '/\'(\d\d)"(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $apos . '$1' . $closing_quote;
117 // '99 '99s '99's (apostrophe) But never '9 or '99% or '999 or '99.0.
118 if ( "'" !== $apos ) {
119 $dynamic[ '/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/' ] = $apos;
122 // Quoted Numbers like '0.42'
123 if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
124 $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $opening_single_quote . '$1' . $closing_single_quote;
127 // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
128 if ( "'" !== $opening_single_quote ) {
129 $dynamic[ '/(?<=\A|[([{"\-]|<|' . $spaces . ')\'/' ] = $opening_single_quote;
132 // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
133 if ( "'" !== $apos ) {
134 $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos;
138 if ( "'" !== $prime ) {
139 $dynamic[ '/(?<=\d)\'/' ] = $prime;
142 // Single quotes followed by spaces or ending punctuation.
143 if ( "'" !== $closing_single_quote ) {
144 $dynamic[ '/\'(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $closing_single_quote;
147 $dynamic_characters['apos'] = array_keys( $dynamic );
148 $dynamic_replacements['apos'] = array_values( $dynamic );
151 // Quoted Numbers like "42"
152 if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
153 $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $opening_quote . '$1' . $closing_quote;
157 if ( '"' !== $double_prime ) {
158 $dynamic[ '/(?<=\d)"/' ] = $double_prime;
161 // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
162 if ( '"' !== $opening_quote ) {
163 $dynamic[ '/(?<=\A|[([{\-]|<|' . $spaces . ')"(?!' . $spaces . ')/' ] = $opening_quote;
166 // Any remaining double quotes.
167 if ( '"' !== $closing_quote ) {
168 $dynamic[ '/"/' ] = $closing_quote;
171 $dynamic_characters['quote'] = array_keys( $dynamic );
172 $dynamic_replacements['quote'] = array_values( $dynamic );
176 $dynamic[ '/---/' ] = $em_dash;
177 $dynamic[ '/(?<=' . $spaces . ')--(?=' . $spaces . ')/' ] = $em_dash;
178 $dynamic[ '/(?<!xn)--/' ] = $en_dash;
179 $dynamic[ '/(?<=' . $spaces . ')-(?=' . $spaces . ')/' ] = $en_dash;
181 $dynamic_characters['dash'] = array_keys( $dynamic );
182 $dynamic_replacements['dash'] = array_values( $dynamic );
185 // Must do this every time in case plugins use these filters in a context sensitive manner
187 * Filter the list of HTML elements not to texturize.
191 * @param array $default_no_texturize_tags An array of HTML element names.
193 $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
195 * Filter the list of shortcodes not to texturize.
199 * @param array $default_no_texturize_shortcodes An array of shortcode names.
201 $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
203 $no_texturize_tags_stack = array();
204 $no_texturize_shortcodes_stack = array();
206 // Look for shortcodes and HTML elements.
208 $tagnames = array_keys( $shortcode_tags );
209 $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
210 $tagregexp = "(?:$tagregexp)(?![\\w-])"; // Excerpt of get_shortcode_regex().
213 '!' // Start of comment, after the <.
214 . '(?:' // Unroll the loop: Consume everything until --> is found.
215 . '-(?!->)' // Dash not followed by end of comment.
216 . '[^\-]*+' // Consume non-dashes.
217 . ')*+' // Loop possessively.
218 . '(?:-->)?'; // End of comment. If not found, match all input.
221 '\[' // Find start of shortcode.
222 . '[\/\[]?' // Shortcodes may begin with [/ or [[
223 . $tagregexp // Only match registered shortcodes, because performance.
225 . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
227 . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
228 . ')*+' // Possessive critical.
229 . '\]' // Find end of shortcode.
230 . '\]?'; // Shortcodes may end with ]]
233 '/(' // Capture the entire match.
234 . '<' // Find start of element.
235 . '(?(?=!--)' // Is this a comment?
236 . $comment_regex // Find end of comment.
238 . '[^>]+>' // Find end of element.
241 . $shortcode_regex // Find shortcodes.
244 $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
246 foreach ( $textarr as &$curl ) {
247 // Only call _wptexturize_pushpop_element if $curl is a delimiter.
249 if ( '<' === $first && '<!--' === substr( $curl, 0, 4 ) ) {
250 // This is an HTML comment delimeter.
254 } elseif ( '<' === $first && '>' === substr( $curl, -1 ) ) {
255 // This is an HTML element delimiter.
257 _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
259 } elseif ( '' === trim( $curl ) ) {
260 // This is a newline between delimiters. Performance improves when we check this.
264 } elseif ( '[' === $first && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
265 // This is a shortcode delimiter.
267 if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
268 // Looks like a normal shortcode.
269 _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
271 // Looks like an escaped shortcode.
275 } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
276 // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
278 $curl = str_replace( $static_characters, $static_replacements, $curl );
280 if ( false !== strpos( $curl, "'" ) ) {
281 $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
283 if ( false !== strpos( $curl, '"' ) ) {
284 $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
286 if ( false !== strpos( $curl, '-' ) ) {
287 $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
290 // 9x9 (times), but never 0x9999
291 if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
292 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
293 $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1×$2', $curl );
297 $text = implode( '', $textarr );
299 // Replace each & with & unless it already looks like an entity.
300 $text = preg_replace('/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $text);
306 * Search for disabled element tags. Push element to stack on tag open and pop
309 * Assumes first char of $text is tag opening and last char is tag closing.
310 * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
315 * @param string $text Text to check. Must be a tag like `<html>` or `[shortcode]`.
316 * @param array $stack List of open tag elements.
317 * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
319 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements) {
320 // Is it an opening tag or closing tag?
321 if ( '/' !== $text[1] ) {
324 } elseif ( 0 == count( $stack ) ) {
325 // Stack is empty. Just stop.
328 $opening_tag = false;
332 // Parse out the tag name.
333 $space = strpos( $text, ' ' );
334 if ( false === $space ) {
337 $space -= $name_offset;
339 $tag = substr( $text, $name_offset, $space );
341 // Handle disabled tags.
342 if ( in_array( $tag, $disabled_elements ) ) {
343 if ( $opening_tag ) {
345 * This disables texturize until we find a closing tag of our type
346 * (e.g. <pre>) even if there was invalid nesting before that
348 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
349 * "baba" won't be texturize
352 array_push( $stack, $tag );
353 } elseif ( end( $stack ) == $tag ) {
360 * Replaces double line-breaks with paragraph elements.
362 * A group of regex replaces used to identify text formatted with newlines and
363 * replace double line-breaks with HTML paragraph tags. The remaining
364 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
369 * @param string $pee The text which has to be formatted.
370 * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
371 * @return string Text which has been converted into correct paragraph tags.
373 function wpautop($pee, $br = true) {
376 if ( trim($pee) === '' )
379 $pee = $pee . "\n"; // just to make things a little easier, pad the end
381 if ( strpos($pee, '<pre') !== false ) {
382 $pee_parts = explode( '</pre>', $pee );
383 $last_pee = array_pop($pee_parts);
387 foreach ( $pee_parts as $pee_part ) {
388 $start = strpos($pee_part, '<pre');
391 if ( $start === false ) {
396 $name = "<pre wp-pre-tag-$i></pre>";
397 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
399 $pee .= substr( $pee_part, 0, $start ) . $name;
406 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
407 // Space things out a little
408 $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|details|menu|summary)';
409 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
410 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
411 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
413 if ( strpos( $pee, '<option' ) !== false ) {
414 // no P/BR around option
415 $pee = preg_replace( '|\s*<option|', '<option', $pee );
416 $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
419 if ( strpos( $pee, '</object>' ) !== false ) {
420 // no P/BR around param and embed
421 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
422 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
423 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
426 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
427 // no P/BR around source and track
428 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
429 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
430 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
433 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
434 // make paragraphs, including one at the end
435 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
438 foreach ( $pees as $tinkle ) {
439 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
442 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
443 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
444 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
445 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
446 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
447 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
448 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
449 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
452 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
453 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
454 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
457 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
458 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
459 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
461 if ( !empty($pre_tags) )
462 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
468 * Newline preservation help function for wpautop
473 * @param array $matches preg_replace_callback matches array
476 function _autop_newline_preservation_helper( $matches ) {
477 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
481 * Don't auto-p wrap shortcodes that stand alone
483 * Ensures that shortcodes are not wrapped in `<p>...</p>`.
487 * @param string $pee The content.
488 * @return string The filtered content.
490 function shortcode_unautop( $pee ) {
491 global $shortcode_tags;
493 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
497 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
498 $spaces = wp_spaces_regexp();
502 . '<p>' // Opening paragraph
503 . '(?:' . $spaces . ')*+' // Optional leading whitespace
504 . '(' // 1: The shortcode
505 . '\\[' // Opening bracket
506 . "($tagregexp)" // 2: Shortcode name
507 . '(?![\\w-])' // Not followed by word character or hyphen
508 // Unroll the loop: Inside the opening shortcode tag
509 . '[^\\]\\/]*' // Not a closing bracket or forward slash
511 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
512 . '[^\\]\\/]*' // Not a closing bracket or forward slash
515 . '\\/\\]' // Self closing tag and closing bracket
517 . '\\]' // Closing bracket
518 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
519 . '[^\\[]*+' // Not an opening bracket
521 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
522 . '[^\\[]*+' // Not an opening bracket
524 . '\\[\\/\\2\\]' // Closing shortcode tag
528 . '(?:' . $spaces . ')*+' // optional trailing whitespace
529 . '<\\/p>' // closing paragraph
532 return preg_replace( $pattern, '$1', $pee );
536 * Checks to see if a string is utf8 encoded.
538 * NOTE: This function checks for 5-Byte sequences, UTF8
539 * has Bytes Sequences with a maximum length of 4.
541 * @author bmorel at ssi dot fr (modified)
544 * @param string $str The string to be checked
545 * @return bool True if $str fits a UTF-8 model, false otherwise.
547 function seems_utf8($str) {
548 mbstring_binary_safe_encoding();
549 $length = strlen($str);
550 reset_mbstring_encoding();
551 for ($i=0; $i < $length; $i++) {
553 if ($c < 0x80) $n = 0; # 0bbbbbbb
554 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
555 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
556 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
557 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
558 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
559 else return false; # Does not match any model
560 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
561 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
569 * Converts a number of special characters into their HTML entities.
571 * Specifically deals with: &, <, >, ", and '.
573 * $quote_style can be set to ENT_COMPAT to encode " to
574 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
579 * @param string $string The text which is to be encoded.
580 * @param int $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
581 * @param string $charset Optional. The character encoding of the string. Default is false.
582 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
583 * @return string The encoded text with HTML entities.
585 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
586 $string = (string) $string;
588 if ( 0 === strlen( $string ) )
591 // Don't bother if there are no specialchars - saves some processing
592 if ( ! preg_match( '/[&<>"\']/', $string ) )
595 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
596 if ( empty( $quote_style ) )
597 $quote_style = ENT_NOQUOTES;
598 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
599 $quote_style = ENT_QUOTES;
601 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
604 if ( ! isset( $_charset ) ) {
605 $alloptions = wp_load_alloptions();
606 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
608 $charset = $_charset;
611 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
614 $_quote_style = $quote_style;
616 if ( $quote_style === 'double' ) {
617 $quote_style = ENT_COMPAT;
618 $_quote_style = ENT_COMPAT;
619 } elseif ( $quote_style === 'single' ) {
620 $quote_style = ENT_NOQUOTES;
623 // Handle double encoding ourselves
624 if ( $double_encode ) {
625 $string = @htmlspecialchars( $string, $quote_style, $charset );
627 // Decode & into &
628 $string = wp_specialchars_decode( $string, $_quote_style );
630 // Guarantee every &entity; is valid or re-encode the &
631 $string = wp_kses_normalize_entities( $string );
633 // Now re-encode everything except &entity;
634 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
636 for ( $i = 0; $i < count( $string ); $i += 2 )
637 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
639 $string = implode( '', $string );
642 // Backwards compatibility
643 if ( 'single' === $_quote_style )
644 $string = str_replace( "'", ''', $string );
650 * Converts a number of HTML entities into their special characters.
652 * Specifically deals with: &, <, >, ", and '.
654 * $quote_style can be set to ENT_COMPAT to decode " entities,
655 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
659 * @param string $string The text which is to be decoded.
660 * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
661 * @return string The decoded text without HTML entities.
663 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
664 $string = (string) $string;
666 if ( 0 === strlen( $string ) ) {
670 // Don't bother if there are no entities - saves a lot of processing
671 if ( strpos( $string, '&' ) === false ) {
675 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
676 if ( empty( $quote_style ) ) {
677 $quote_style = ENT_NOQUOTES;
678 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
679 $quote_style = ENT_QUOTES;
682 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
683 $single = array( ''' => '\'', ''' => '\'' );
684 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
685 $double = array( '"' => '"', '"' => '"', '"' => '"' );
686 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
687 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
688 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
690 if ( $quote_style === ENT_QUOTES ) {
691 $translation = array_merge( $single, $double, $others );
692 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
693 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
694 $translation = array_merge( $double, $others );
695 $translation_preg = array_merge( $double_preg, $others_preg );
696 } elseif ( $quote_style === 'single' ) {
697 $translation = array_merge( $single, $others );
698 $translation_preg = array_merge( $single_preg, $others_preg );
699 } elseif ( $quote_style === ENT_NOQUOTES ) {
700 $translation = $others;
701 $translation_preg = $others_preg;
704 // Remove zero padding on numeric entities
705 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
707 // Replace characters according to translation table
708 return strtr( $string, $translation );
712 * Checks for invalid UTF8 in a string.
716 * @param string $string The text which is to be checked.
717 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
718 * @return string The checked text.
720 function wp_check_invalid_utf8( $string, $strip = false ) {
721 $string = (string) $string;
723 if ( 0 === strlen( $string ) ) {
727 // Store the site charset as a static to avoid multiple calls to get_option()
729 if ( !isset( $is_utf8 ) ) {
730 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
736 // Check for support for utf8 in the installed PCRE library once and store the result in a static
738 if ( !isset( $utf8_pcre ) ) {
739 $utf8_pcre = @preg_match( '/^./u', 'a' );
741 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
746 // preg_match fails when it encounters invalid UTF8 in $string
747 if ( 1 === @preg_match( '/^./us', $string ) ) {
751 // Attempt to strip the bad chars if requested (not recommended)
752 if ( $strip && function_exists( 'iconv' ) ) {
753 return iconv( 'utf-8', 'utf-8', $string );
760 * Encode the Unicode values to be used in the URI.
764 * @param string $utf8_string
765 * @param int $length Max length of the string
766 * @return string String with Unicode encoded for URI.
768 function utf8_uri_encode( $utf8_string, $length = 0 ) {
774 mbstring_binary_safe_encoding();
775 $string_length = strlen( $utf8_string );
776 reset_mbstring_encoding();
778 for ($i = 0; $i < $string_length; $i++ ) {
780 $value = ord( $utf8_string[ $i ] );
782 if ( $value < 128 ) {
783 if ( $length && ( $unicode_length >= $length ) )
785 $unicode .= chr($value);
788 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
792 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
794 if ( count( $values ) == $num_octets ) {
795 if ($num_octets == 3) {
796 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
797 $unicode_length += 9;
799 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
800 $unicode_length += 6;
813 * Converts all accent characters to ASCII characters.
815 * If there are no accent characters, then the string given is just returned.
819 * @param string $string Text that might have accent characters
820 * @return string Filtered string with replaced "nice" characters.
822 function remove_accents($string) {
823 if ( !preg_match('/[\x80-\xff]/', $string) )
826 if (seems_utf8($string)) {
828 // Decompositions for Latin-1 Supplement
829 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
830 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
831 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
832 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
833 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
834 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
835 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
836 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
837 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
838 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
839 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
840 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
841 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
842 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
843 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
844 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
845 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
846 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
847 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
848 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
849 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
850 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
851 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
852 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
853 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
854 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
855 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
856 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
857 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
858 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
859 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
860 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
861 // Decompositions for Latin Extended-A
862 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
863 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
864 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
865 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
866 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
867 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
868 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
869 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
870 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
871 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
872 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
873 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
874 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
875 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
876 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
877 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
878 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
879 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
880 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
881 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
882 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
883 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
884 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
885 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
886 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
887 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
888 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
889 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
890 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
891 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
892 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
893 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
894 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
895 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
896 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
897 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
898 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
899 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
900 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
901 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
902 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
903 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
904 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
905 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
906 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
907 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
908 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
909 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
910 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
911 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
912 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
913 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
914 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
915 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
916 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
917 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
918 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
919 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
920 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
921 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
922 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
923 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
924 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
925 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
926 // Decompositions for Latin Extended-B
927 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
928 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
930 chr(226).chr(130).chr(172) => 'E',
932 chr(194).chr(163) => '',
933 // Vowels with diacritic (Vietnamese)
935 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
936 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
938 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
939 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
940 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
941 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
942 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
943 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
944 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
946 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
947 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
948 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
949 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
950 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
951 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
952 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
953 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
954 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
955 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
956 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
957 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
959 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
960 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
961 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
962 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
963 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
964 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
965 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
966 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
968 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
969 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
970 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
971 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
972 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
973 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
975 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
976 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
977 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
978 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
979 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
980 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
981 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
982 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
983 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
984 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
985 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
986 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
987 // Vowels with diacritic (Chinese, Hanyu Pinyin)
988 chr(201).chr(145) => 'a',
990 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
992 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
994 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
995 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
996 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
997 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
998 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
1000 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
1003 // Used for locale-specific rules
1004 $locale = get_locale();
1006 if ( 'de_DE' == $locale ) {
1007 $chars[ chr(195).chr(132) ] = 'Ae';
1008 $chars[ chr(195).chr(164) ] = 'ae';
1009 $chars[ chr(195).chr(150) ] = 'Oe';
1010 $chars[ chr(195).chr(182) ] = 'oe';
1011 $chars[ chr(195).chr(156) ] = 'Ue';
1012 $chars[ chr(195).chr(188) ] = 'ue';
1013 $chars[ chr(195).chr(159) ] = 'ss';
1014 } elseif ( 'da_DK' === $locale ) {
1015 $chars[ chr(195).chr(134) ] = 'Ae';
1016 $chars[ chr(195).chr(166) ] = 'ae';
1017 $chars[ chr(195).chr(152) ] = 'Oe';
1018 $chars[ chr(195).chr(184) ] = 'oe';
1019 $chars[ chr(195).chr(133) ] = 'Aa';
1020 $chars[ chr(195).chr(165) ] = 'aa';
1023 $string = strtr($string, $chars);
1025 // Assume ISO-8859-1 if not UTF-8
1026 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1027 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1028 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1029 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1030 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1031 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1032 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1033 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1034 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1035 .chr(252).chr(253).chr(255);
1037 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1039 $string = strtr($string, $chars['in'], $chars['out']);
1040 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1041 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1042 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1049 * Sanitizes a filename, replacing whitespace with dashes.
1051 * Removes special characters that are illegal in filenames on certain
1052 * operating systems and special characters requiring special escaping
1053 * to manipulate at the command line. Replaces spaces and consecutive
1054 * dashes with a single dash. Trims period, dash and underscore from beginning
1055 * and end of filename.
1059 * @param string $filename The filename to be sanitized
1060 * @return string The sanitized filename
1062 function sanitize_file_name( $filename ) {
1063 $filename_raw = $filename;
1064 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1066 * Filter the list of characters to remove from a filename.
1070 * @param array $special_chars Characters to remove.
1071 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1073 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1074 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1075 $filename = str_replace( $special_chars, '', $filename );
1076 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1077 $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
1078 $filename = trim( $filename, '.-_' );
1080 // Split the filename into a base and extension[s]
1081 $parts = explode('.', $filename);
1083 // Return if only one extension
1084 if ( count( $parts ) <= 2 ) {
1086 * Filter a sanitized filename string.
1090 * @param string $filename Sanitized filename.
1091 * @param string $filename_raw The filename prior to sanitization.
1093 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1096 // Process multiple extensions
1097 $filename = array_shift($parts);
1098 $extension = array_pop($parts);
1099 $mimes = get_allowed_mime_types();
1102 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1103 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1105 foreach ( (array) $parts as $part) {
1106 $filename .= '.' . $part;
1108 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1110 foreach ( $mimes as $ext_preg => $mime_match ) {
1111 $ext_preg = '!^(' . $ext_preg . ')$!i';
1112 if ( preg_match( $ext_preg, $part ) ) {
1121 $filename .= '.' . $extension;
1122 /** This filter is documented in wp-includes/formatting.php */
1123 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1127 * Sanitizes a username, stripping out unsafe characters.
1129 * Removes tags, octets, entities, and if strict is enabled, will only keep
1130 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1131 * raw username (the username in the parameter), and the value of $strict as
1132 * parameters for the 'sanitize_user' filter.
1136 * @param string $username The username to be sanitized.
1137 * @param bool $strict If set limits $username to specific characters. Default false.
1138 * @return string The sanitized username, after passing through filters.
1140 function sanitize_user( $username, $strict = false ) {
1141 $raw_username = $username;
1142 $username = wp_strip_all_tags( $username );
1143 $username = remove_accents( $username );
1145 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1146 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1148 // If strict, reduce to ASCII for max portability.
1150 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1152 $username = trim( $username );
1153 // Consolidate contiguous whitespace
1154 $username = preg_replace( '|\s+|', ' ', $username );
1157 * Filter a sanitized username string.
1161 * @param string $username Sanitized username.
1162 * @param string $raw_username The username prior to sanitization.
1163 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1165 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1169 * Sanitizes a string key.
1171 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1175 * @param string $key String key
1176 * @return string Sanitized key
1178 function sanitize_key( $key ) {
1180 $key = strtolower( $key );
1181 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1184 * Filter a sanitized key string.
1188 * @param string $key Sanitized key.
1189 * @param string $raw_key The key prior to sanitization.
1191 return apply_filters( 'sanitize_key', $key, $raw_key );
1195 * Sanitizes a title, or returns a fallback title.
1197 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1198 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1203 * @param string $title The string to be sanitized.
1204 * @param string $fallback_title Optional. A title to use if $title is empty.
1205 * @param string $context Optional. The operation for which the string is sanitized
1206 * @return string The sanitized string.
1208 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1209 $raw_title = $title;
1211 if ( 'save' == $context )
1212 $title = remove_accents($title);
1215 * Filter a sanitized title string.
1219 * @param string $title Sanitized title.
1220 * @param string $raw_title The title prior to sanitization.
1221 * @param string $context The context for which the title is being sanitized.
1223 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1225 if ( '' === $title || false === $title )
1226 $title = $fallback_title;
1232 * Sanitizes a title with the 'query' context.
1234 * Used for querying the database for a value from URL.
1238 * @param string $title The string to be sanitized.
1239 * @return string The sanitized string.
1241 function sanitize_title_for_query( $title ) {
1242 return sanitize_title( $title, '', 'query' );
1246 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1248 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1249 * Whitespace becomes a dash.
1253 * @param string $title The title to be sanitized.
1254 * @param string $raw_title Optional. Not used.
1255 * @param string $context Optional. The operation for which the string is sanitized.
1256 * @return string The sanitized title.
1258 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1259 $title = strip_tags($title);
1260 // Preserve escaped octets.
1261 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1262 // Remove percent signs that are not part of an octet.
1263 $title = str_replace('%', '', $title);
1265 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1267 if (seems_utf8($title)) {
1268 if (function_exists('mb_strtolower')) {
1269 $title = mb_strtolower($title, 'UTF-8');
1271 $title = utf8_uri_encode($title, 200);
1274 $title = strtolower($title);
1275 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1276 $title = str_replace('.', '-', $title);
1278 if ( 'save' == $context ) {
1279 // Convert nbsp, ndash and mdash to hyphens
1280 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1282 // Strip these characters entirely
1283 $title = str_replace( array(
1287 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1289 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1290 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1291 // copy, reg, deg, hellip and trade
1292 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1294 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1295 // grave accent, macron, caron
1296 '%cc%80', '%cc%84', '%cc%8c',
1299 // Convert times to x
1300 $title = str_replace( '%c3%97', 'x', $title );
1303 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1304 $title = preg_replace('/\s+/', '-', $title);
1305 $title = preg_replace('|-+|', '-', $title);
1306 $title = trim($title, '-');
1312 * Ensures a string is a valid SQL order by clause.
1314 * Accepts one or more columns, with or without ASC/DESC, and also accepts
1319 * @param string $orderby Order by string to be checked.
1320 * @return false|string Returns the order by clause if it is a match, false otherwise.
1322 function sanitize_sql_orderby( $orderby ){
1323 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
1330 * Sanitizes an HTML classname to ensure it only contains valid characters.
1332 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1333 * string then it will return the alternative value supplied.
1335 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1339 * @param string $class The classname to be sanitized
1340 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1341 * Defaults to an empty string.
1342 * @return string The sanitized value
1344 function sanitize_html_class( $class, $fallback = '' ) {
1345 //Strip out any % encoded octets
1346 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1348 //Limit to A-Z,a-z,0-9,_,-
1349 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1351 if ( '' == $sanitized )
1352 $sanitized = $fallback;
1355 * Filter a sanitized HTML class string.
1359 * @param string $sanitized The sanitized HTML class.
1360 * @param string $class HTML class before sanitization.
1361 * @param string $fallback The fallback string.
1363 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1367 * Converts a number of characters from a string.
1369 * Metadata tags `<title>` and `<category>` are removed, `<br>` and `<hr>` are
1370 * converted into correct XHTML and Unicode characters are converted to the
1375 * @param string $content String of characters to be converted.
1376 * @param string $deprecated Not used.
1377 * @return string Converted string.
1379 function convert_chars($content, $deprecated = '') {
1380 if ( !empty( $deprecated ) )
1381 _deprecated_argument( __FUNCTION__, '0.71' );
1383 // Translation of invalid Unicode references range to valid range
1384 $wp_htmltranswinuni = array(
1385 '€' => '€', // the Euro sign
1387 '‚' => '‚', // these are Windows CP1252 specific characters
1388 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1389 '„' => '„',
1390 '…' => '…',
1391 '†' => '†',
1392 '‡' => '‡',
1393 'ˆ' => 'ˆ',
1394 '‰' => '‰',
1395 'Š' => 'Š',
1396 '‹' => '‹',
1397 'Œ' => 'Œ',
1399 'Ž' => 'Ž',
1402 '‘' => '‘',
1403 '’' => '’',
1404 '“' => '“',
1405 '”' => '”',
1406 '•' => '•',
1407 '–' => '–',
1408 '—' => '—',
1409 '˜' => '˜',
1410 '™' => '™',
1411 'š' => 'š',
1412 '›' => '›',
1413 'œ' => 'œ',
1415 'ž' => 'ž',
1416 'Ÿ' => 'Ÿ'
1419 // Remove metadata tags
1420 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1421 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1423 // Converts lone & characters into & (a.k.a. &)
1424 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1427 $content = strtr($content, $wp_htmltranswinuni);
1429 // Just a little XHTML help
1430 $content = str_replace('<br>', '<br />', $content);
1431 $content = str_replace('<hr>', '<hr />', $content);
1437 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1441 * @param string $text Text to be balanced
1442 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1443 * @return string Balanced text
1445 function balanceTags( $text, $force = false ) {
1446 if ( $force || get_option('use_balanceTags') == 1 ) {
1447 return force_balance_tags( $text );
1454 * Balances tags of string using a modified stack.
1458 * @author Leonard Lin <leonard@acm.org>
1460 * @copyright November 4, 2001
1462 * @todo Make better - change loop condition to $text in 1.2
1463 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1464 * 1.1 Fixed handling of append/stack pop order of end text
1465 * Added Cleaning Hooks
1468 * @param string $text Text to be balanced.
1469 * @return string Balanced text.
1471 function force_balance_tags( $text ) {
1472 $tagstack = array();
1476 // Known single-entity/self-closing tags
1477 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1478 // Tags that can be immediately nested within themselves
1479 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1481 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1482 $text = str_replace('< !--', '< !--', $text);
1483 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1484 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1486 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1487 $newtext .= $tagqueue;
1489 $i = strpos($text, $regex[0]);
1490 $l = strlen($regex[0]);
1492 // clear the shifter
1495 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1496 $tag = strtolower(substr($regex[1],1));
1497 // if too many closing tags
1498 if( $stacksize <= 0 ) {
1500 // or close to be safe $tag = '/' . $tag;
1502 // if stacktop value = tag close value then pop
1503 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1504 $tag = '</' . $tag . '>'; // Close Tag
1506 array_pop( $tagstack );
1508 } else { // closing tag not at top, search for it
1509 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1510 if ( $tagstack[$j] == $tag ) {
1511 // add tag to tagqueue
1512 for ( $k = $stacksize-1; $k >= $j; $k--) {
1513 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1521 } else { // Begin Tag
1522 $tag = strtolower($regex[1]);
1526 // If it's an empty tag "< >", do nothing
1530 // ElseIf it presents itself as a self-closing tag...
1531 elseif ( substr( $regex[2], -1 ) == '/' ) {
1532 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1533 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1534 if ( ! in_array( $tag, $single_tags ) )
1535 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1537 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1538 elseif ( in_array($tag, $single_tags) ) {
1541 // Else it's not a single-entity tag
1543 // If the top of the stack is the same as the tag we want to push, close previous tag
1544 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1545 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1548 $stacksize = array_push( $tagstack, $tag );
1552 $attributes = $regex[2];
1553 if( ! empty( $attributes ) && $attributes[0] != '>' )
1554 $attributes = ' ' . $attributes;
1556 $tag = '<' . $tag . $attributes . '>';
1557 //If already queuing a close tag, then put this tag on, too
1558 if ( !empty($tagqueue) ) {
1563 $newtext .= substr($text, 0, $i) . $tag;
1564 $text = substr($text, $i + $l);
1568 $newtext .= $tagqueue;
1570 // Add Remaining text
1574 while( $x = array_pop($tagstack) )
1575 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1577 // WP fix for the bug with HTML comments
1578 $newtext = str_replace("< !--","<!--",$newtext);
1579 $newtext = str_replace("< !--","< !--",$newtext);
1585 * Acts on text which is about to be edited.
1587 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1588 * to convert special characters to HTML entities. If $richedit is set to true,
1589 * it is simply a holder for the 'format_to_edit' filter.
1593 * @param string $content The text about to be edited.
1594 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1595 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1597 function format_to_edit( $content, $richedit = false ) {
1599 * Filter the text to be formatted for editing.
1603 * @param string $content The text, prior to formatting for editing.
1605 $content = apply_filters( 'format_to_edit', $content );
1607 $content = esc_textarea( $content );
1612 * Add leading zeros when necessary.
1614 * If you set the threshold to '4' and the number is '10', then you will get
1615 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1616 * will get back '5000'.
1618 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1619 * and the size of the number. If the number is large enough, then no zeros will
1624 * @param mixed $number Number to append zeros to if not greater than threshold.
1625 * @param int $threshold Digit places number needs to be to not have zeros added.
1626 * @return string Adds leading zeros to number if needed.
1628 function zeroise($number, $threshold) {
1629 return sprintf('%0'.$threshold.'s', $number);
1633 * Adds backslashes before letters and before a number at the start of a string.
1637 * @param string $string Value to which backslashes will be added.
1638 * @return string String with backslashes inserted.
1640 function backslashit($string) {
1641 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1642 $string = '\\\\' . $string;
1643 return addcslashes( $string, 'A..Za..z' );
1647 * Appends a trailing slash.
1649 * Will remove trailing forward and backslashes if it exists already before adding
1650 * a trailing forward slash. This prevents double slashing a string or path.
1652 * The primary use of this is for paths and thus should be used for paths. It is
1653 * not restricted to paths and offers no specific path support.
1657 * @param string $string What to add the trailing slash to.
1658 * @return string String with trailing slash added.
1660 function trailingslashit( $string ) {
1661 return untrailingslashit( $string ) . '/';
1665 * Removes trailing forward slashes and backslashes if they exist.
1667 * The primary use of this is for paths and thus should be used for paths. It is
1668 * not restricted to paths and offers no specific path support.
1672 * @param string $string What to remove the trailing slashes from.
1673 * @return string String without the trailing slashes.
1675 function untrailingslashit( $string ) {
1676 return rtrim( $string, '/\\' );
1680 * Adds slashes to escape strings.
1682 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1683 * http://www.php.net/magic_quotes} for more details.
1687 * @param string $gpc The string returned from HTTP request data.
1688 * @return string Returns a string escaped with slashes.
1690 function addslashes_gpc($gpc) {
1691 if ( get_magic_quotes_gpc() )
1692 $gpc = stripslashes($gpc);
1694 return wp_slash($gpc);
1698 * Navigates through an array and removes slashes from the values.
1700 * If an array is passed, the array_map() function causes a callback to pass the
1701 * value back to the function. The slashes from this value will removed.
1705 * @param mixed $value The value to be stripped.
1706 * @return mixed Stripped value.
1708 function stripslashes_deep($value) {
1709 if ( is_array($value) ) {
1710 $value = array_map('stripslashes_deep', $value);
1711 } elseif ( is_object($value) ) {
1712 $vars = get_object_vars( $value );
1713 foreach ($vars as $key=>$data) {
1714 $value->{$key} = stripslashes_deep( $data );
1716 } elseif ( is_string( $value ) ) {
1717 $value = stripslashes($value);
1724 * Navigates through an array and encodes the values to be used in a URL.
1729 * @param array|string $value The array or string to be encoded.
1730 * @return array|string $value The encoded array (or string from the callback).
1732 function urlencode_deep($value) {
1733 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1738 * Navigates through an array and raw encodes the values to be used in a URL.
1742 * @param array|string $value The array or string to be encoded.
1743 * @return array|string $value The encoded array (or string from the callback).
1745 function rawurlencode_deep( $value ) {
1746 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1750 * Converts email addresses characters to HTML entities to block spam bots.
1754 * @param string $email_address Email address.
1755 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
1756 * @return string Converted email address.
1758 function antispambot( $email_address, $hex_encoding = 0 ) {
1759 $email_no_spam_address = '';
1760 for ( $i = 0; $i < strlen( $email_address ); $i++ ) {
1761 $j = rand( 0, 1 + $hex_encoding );
1763 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
1764 } elseif ( $j == 1 ) {
1765 $email_no_spam_address .= $email_address[$i];
1766 } elseif ( $j == 2 ) {
1767 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
1771 $email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
1773 return $email_no_spam_address;
1777 * Callback to convert URI match to HTML A element.
1779 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1780 * make_clickable()}.
1785 * @param array $matches Single Regex Match.
1786 * @return string HTML A element with URI address.
1788 function _make_url_clickable_cb($matches) {
1791 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1792 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1793 // Then we can let the parenthesis balancer do its thing below.
1794 $url .= $matches[3];
1797 $suffix = $matches[3];
1800 // Include parentheses in the URL only if paired
1801 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1802 $suffix = strrchr( $url, ')' ) . $suffix;
1803 $url = substr( $url, 0, strrpos( $url, ')' ) );
1806 $url = esc_url($url);
1810 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1814 * Callback to convert URL match to HTML A element.
1816 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1817 * make_clickable()}.
1822 * @param array $matches Single Regex Match.
1823 * @return string HTML A element with URL address.
1825 function _make_web_ftp_clickable_cb($matches) {
1827 $dest = $matches[2];
1828 $dest = 'http://' . $dest;
1829 $dest = esc_url($dest);
1833 // removed trailing [.,;:)] from URL
1834 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1835 $ret = substr($dest, -1);
1836 $dest = substr($dest, 0, strlen($dest)-1);
1838 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1842 * Callback to convert email address match to HTML A element.
1844 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1845 * make_clickable()}.
1850 * @param array $matches Single Regex Match.
1851 * @return string HTML A element with email address.
1853 function _make_email_clickable_cb($matches) {
1854 $email = $matches[2] . '@' . $matches[3];
1855 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1859 * Convert plaintext URI to HTML links.
1861 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1866 * @param string $text Content to convert URIs.
1867 * @return string Content with converted URIs.
1869 function make_clickable( $text ) {
1871 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
1872 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
1873 foreach ( $textarr as $piece ) {
1875 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
1877 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
1880 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
1885 // Long strings might contain expensive edge cases ...
1886 if ( 10000 < strlen( $piece ) ) {
1888 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
1889 if ( 2101 < strlen( $chunk ) ) {
1890 $r .= $chunk; // Too big, no whitespace: bail.
1892 $r .= make_clickable( $chunk );
1896 $ret = " $piece "; // Pad with whitespace to simplify the regexes
1899 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
1901 [\\w]{1,20}+:// # Scheme and hier-part prefix
1902 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
1903 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
1904 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
1905 [\'.,;:!?)] # Punctuation URL character
1906 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
1909 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
1910 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
1911 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
1913 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
1915 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
1916 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
1918 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
1923 // Cleanup of accidental links within links
1924 $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
1929 * Breaks a string into chunks by splitting at whitespace characters.
1930 * The length of each returned chunk is as close to the specified length goal as possible,
1931 * with the caveat that each chunk includes its trailing delimiter.
1932 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
1934 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
1936 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
1938 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
1940 * 0 => '1234 67890 ', // 11 characters: Perfect split
1941 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
1942 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
1943 * 3 => '1234 890 ', // 11 characters: Perfect split
1944 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
1945 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
1946 * 6 => ' 45678 ', // 11 characters: Perfect split
1947 * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
1953 * @param string $string The string to split.
1954 * @param int $goal The desired chunk length.
1955 * @return array Numeric array of chunks.
1957 function _split_str_by_whitespace( $string, $goal ) {
1960 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
1962 while ( $goal < strlen( $string_nullspace ) ) {
1963 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
1965 if ( false === $pos ) {
1966 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
1967 if ( false === $pos ) {
1972 $chunks[] = substr( $string, 0, $pos + 1 );
1973 $string = substr( $string, $pos + 1 );
1974 $string_nullspace = substr( $string_nullspace, $pos + 1 );
1978 $chunks[] = $string;
1985 * Adds rel nofollow string to all HTML A elements in content.
1989 * @param string $text Content that may contain HTML A elements.
1990 * @return string Converted content.
1992 function wp_rel_nofollow( $text ) {
1993 // This is a pre save filter, so text is already escaped.
1994 $text = stripslashes($text);
1995 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1996 $text = wp_slash($text);
2001 * Callback to add rel=nofollow string to HTML A element.
2003 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2004 * string to prevent from invalidating (X)HTML.
2008 * @param array $matches Single Match
2009 * @return string HTML A Element with rel nofollow.
2011 function wp_rel_nofollow_callback( $matches ) {
2012 $text = $matches[1];
2013 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
2014 return "<a $text rel=\"nofollow\">";
2018 * Convert one smiley code to the icon graphic file equivalent.
2020 * Callback handler for {@link convert_smilies()}.
2021 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2022 * `<img>` string for that smiley.
2024 * @global array $wpsmiliestrans
2027 * @param array $matches Single match. Smiley code to convert to image.
2028 * @return string Image string for smiley.
2030 function translate_smiley( $matches ) {
2031 global $wpsmiliestrans;
2033 if ( count( $matches ) == 0 )
2036 $smiley = trim( reset( $matches ) );
2037 $img = $wpsmiliestrans[ $smiley ];
2040 * Filter the Smiley image URL before it's used in the image element.
2044 * @param string $smiley_url URL for the smiley image.
2045 * @param string $img Filename for the smiley image.
2046 * @param string $site_url Site URL, as returned by site_url().
2048 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2050 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" />', esc_url( $src_url ), esc_attr( $smiley ) );
2054 * Convert text equivalent of smilies to images.
2056 * Will only convert smilies if the option 'use_smilies' is true and the global
2057 * used in the function isn't empty.
2060 * @uses $wp_smiliessearch
2062 * @param string $text Content to convert smilies from text.
2063 * @return string Converted content with text smilies replaced with images.
2065 function convert_smilies( $text ) {
2066 global $wp_smiliessearch;
2068 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2069 // HTML loop taken from texturize function, could possible be consolidated
2070 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2071 $stop = count( $textarr );// loop stuff
2073 // Ignore proessing of specific tags
2074 $tags_to_ignore = 'code|pre|style|script|textarea';
2075 $ignore_block_element = '';
2077 for ( $i = 0; $i < $stop; $i++ ) {
2078 $content = $textarr[$i];
2080 // If we're in an ignore block, wait until we find its closing tag
2081 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2082 $ignore_block_element = $matches[1];
2085 // If it's not a tag and not in ignore block
2086 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2087 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2090 // did we exit ignore block
2091 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2092 $ignore_block_element = '';
2095 $output .= $content;
2098 // return default text.
2105 * Verifies that an email is valid.
2107 * Does not grok i18n domains. Not RFC compliant.
2111 * @param string $email Email address to verify.
2112 * @param boolean $deprecated Deprecated.
2113 * @return string|bool Either false or the valid email address.
2115 function is_email( $email, $deprecated = false ) {
2116 if ( ! empty( $deprecated ) )
2117 _deprecated_argument( __FUNCTION__, '3.0' );
2119 // Test for the minimum length the email can be
2120 if ( strlen( $email ) < 3 ) {
2122 * Filter whether an email address is valid.
2124 * This filter is evaluated under several different contexts, such as 'email_too_short',
2125 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2126 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2130 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2131 * @param string $email The email address being checked.
2132 * @param string $message An explanatory message to the user.
2133 * @param string $context Context under which the email was tested.
2135 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2138 // Test for an @ character after the first position
2139 if ( strpos( $email, '@', 1 ) === false ) {
2140 /** This filter is documented in wp-includes/formatting.php */
2141 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2144 // Split out the local and domain parts
2145 list( $local, $domain ) = explode( '@', $email, 2 );
2148 // Test for invalid characters
2149 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2150 /** This filter is documented in wp-includes/formatting.php */
2151 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2155 // Test for sequences of periods
2156 if ( preg_match( '/\.{2,}/', $domain ) ) {
2157 /** This filter is documented in wp-includes/formatting.php */
2158 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2161 // Test for leading and trailing periods and whitespace
2162 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2163 /** This filter is documented in wp-includes/formatting.php */
2164 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2167 // Split the domain into subs
2168 $subs = explode( '.', $domain );
2170 // Assume the domain will have at least two subs
2171 if ( 2 > count( $subs ) ) {
2172 /** This filter is documented in wp-includes/formatting.php */
2173 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2176 // Loop through each sub
2177 foreach ( $subs as $sub ) {
2178 // Test for leading and trailing hyphens and whitespace
2179 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2180 /** This filter is documented in wp-includes/formatting.php */
2181 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2184 // Test for invalid characters
2185 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2186 /** This filter is documented in wp-includes/formatting.php */
2187 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2191 // Congratulations your email made it!
2192 /** This filter is documented in wp-includes/formatting.php */
2193 return apply_filters( 'is_email', $email, $email, null );
2197 * Convert to ASCII from email subjects.
2201 * @param string $string Subject line
2202 * @return string Converted string to ASCII
2204 function wp_iso_descrambler($string) {
2205 /* this may only work with iso-8859-1, I'm afraid */
2206 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2209 $subject = str_replace('_', ' ', $matches[2]);
2210 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
2216 * Helper function to convert hex encoded chars to ASCII
2221 * @param array $match The preg_replace_callback matches array
2222 * @return string Converted chars
2224 function _wp_iso_convert( $match ) {
2225 return chr( hexdec( strtolower( $match[1] ) ) );
2229 * Returns a date in the GMT equivalent.
2231 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2232 * timezone_string available, the date is assumed to be in that timezone,
2233 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2234 * format can be overridden using the $format parameter.
2238 * @param string $string The date to be converted.
2239 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2240 * @return string GMT version of the date provided.
2242 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2243 $tz = get_option( 'timezone_string' );
2245 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2247 return gmdate( $format, 0 );
2248 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2249 $string_gmt = $datetime->format( $format );
2251 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 ) )
2252 return gmdate( $format, 0 );
2253 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2254 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2260 * Converts a GMT date into the correct format for the blog.
2262 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2263 * timezone_string available, the returned date is in that timezone, otherwise
2264 * it simply adds the value of gmt_offset. Return format can be overridden
2265 * using the $format parameter
2269 * @param string $string The date to be converted.
2270 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2271 * @return string Formatted date relative to the timezone / GMT offset.
2273 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2274 $tz = get_option( 'timezone_string' );
2276 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2278 return date( $format, 0 );
2279 $datetime->setTimezone( new DateTimeZone( $tz ) );
2280 $string_localtime = $datetime->format( $format );
2282 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) )
2283 return date( $format, 0 );
2284 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2285 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2287 return $string_localtime;
2291 * Computes an offset in seconds from an iso8601 timezone.
2295 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2296 * @return int|float The offset in seconds.
2298 function iso8601_timezone_to_offset($timezone) {
2299 // $timezone is either 'Z' or '[+|-]hhmm'
2300 if ($timezone == 'Z') {
2303 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2304 $hours = intval(substr($timezone, 1, 2));
2305 $minutes = intval(substr($timezone, 3, 4)) / 60;
2306 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2312 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2316 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2317 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2318 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2320 function iso8601_to_datetime($date_string, $timezone = 'user') {
2321 $timezone = strtolower($timezone);
2323 if ($timezone == 'gmt') {
2325 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);
2327 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2328 $offset = iso8601_timezone_to_offset($date_bits[7]);
2329 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2330 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2333 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2334 $timestamp -= $offset;
2336 return gmdate('Y-m-d H:i:s', $timestamp);
2338 } else if ($timezone == 'user') {
2339 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);
2344 * Adds a element attributes to open links in new windows.
2346 * Comment text in popup windows should be filtered through this. Right now it's
2347 * a moderately dumb function, ideally it would detect whether a target or rel
2348 * attribute was already there and adjust its actions accordingly.
2352 * @param string $text Content to replace links to open in a new window.
2353 * @return string Content that has filtered links.
2355 function popuplinks($text) {
2356 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2361 * Strips out all characters that are not allowable in an email.
2365 * @param string $email Email address to filter.
2366 * @return string Filtered email address.
2368 function sanitize_email( $email ) {
2369 // Test for the minimum length the email can be
2370 if ( strlen( $email ) < 3 ) {
2372 * Filter a sanitized email address.
2374 * This filter is evaluated under several contexts, including 'email_too_short',
2375 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2376 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2380 * @param string $email The sanitized email address.
2381 * @param string $email The email address, as provided to sanitize_email().
2382 * @param string $message A message to pass to the user.
2384 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2387 // Test for an @ character after the first position
2388 if ( strpos( $email, '@', 1 ) === false ) {
2389 /** This filter is documented in wp-includes/formatting.php */
2390 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2393 // Split out the local and domain parts
2394 list( $local, $domain ) = explode( '@', $email, 2 );
2397 // Test for invalid characters
2398 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2399 if ( '' === $local ) {
2400 /** This filter is documented in wp-includes/formatting.php */
2401 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2405 // Test for sequences of periods
2406 $domain = preg_replace( '/\.{2,}/', '', $domain );
2407 if ( '' === $domain ) {
2408 /** This filter is documented in wp-includes/formatting.php */
2409 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2412 // Test for leading and trailing periods and whitespace
2413 $domain = trim( $domain, " \t\n\r\0\x0B." );
2414 if ( '' === $domain ) {
2415 /** This filter is documented in wp-includes/formatting.php */
2416 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2419 // Split the domain into subs
2420 $subs = explode( '.', $domain );
2422 // Assume the domain will have at least two subs
2423 if ( 2 > count( $subs ) ) {
2424 /** This filter is documented in wp-includes/formatting.php */
2425 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2428 // Create an array that will contain valid subs
2429 $new_subs = array();
2431 // Loop through each sub
2432 foreach ( $subs as $sub ) {
2433 // Test for leading and trailing hyphens
2434 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2436 // Test for invalid characters
2437 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2439 // If there's anything left, add it to the valid subs
2440 if ( '' !== $sub ) {
2445 // If there aren't 2 or more valid subs
2446 if ( 2 > count( $new_subs ) ) {
2447 /** This filter is documented in wp-includes/formatting.php */
2448 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2451 // Join valid subs into the new domain
2452 $domain = join( '.', $new_subs );
2454 // Put the email back together
2455 $email = $local . '@' . $domain;
2457 // Congratulations your email made it!
2458 /** This filter is documented in wp-includes/formatting.php */
2459 return apply_filters( 'sanitize_email', $email, $email, null );
2463 * Determines the difference between two timestamps.
2465 * The difference is returned in a human readable format such as "1 hour",
2466 * "5 mins", "2 days".
2470 * @param int $from Unix timestamp from which the difference begins.
2471 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2472 * @return string Human readable time difference.
2474 function human_time_diff( $from, $to = '' ) {
2475 if ( empty( $to ) ) {
2479 $diff = (int) abs( $to - $from );
2481 if ( $diff < HOUR_IN_SECONDS ) {
2482 $mins = round( $diff / MINUTE_IN_SECONDS );
2485 /* translators: min=minute */
2486 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2487 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2488 $hours = round( $diff / HOUR_IN_SECONDS );
2491 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2492 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2493 $days = round( $diff / DAY_IN_SECONDS );
2496 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2497 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2498 $weeks = round( $diff / WEEK_IN_SECONDS );
2501 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2502 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2503 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2506 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2507 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2508 $years = round( $diff / YEAR_IN_SECONDS );
2511 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2515 * Filter the human readable difference between two timestamps.
2519 * @param string $since The difference in human readable text.
2520 * @param int $diff The difference in seconds.
2521 * @param int $from Unix timestamp from which the difference begins.
2522 * @param int $to Unix timestamp to end the time difference.
2524 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2528 * Generates an excerpt from the content, if needed.
2530 * The excerpt word amount will be 55 words and if the amount is greater than
2531 * that, then the string ' […]' will be appended to the excerpt. If the string
2532 * is less than 55 words, then the content will be returned as is.
2534 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2535 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2539 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2540 * @return string The excerpt.
2542 function wp_trim_excerpt($text = '') {
2543 $raw_excerpt = $text;
2544 if ( '' == $text ) {
2545 $text = get_the_content('');
2547 $text = strip_shortcodes( $text );
2549 /** This filter is documented in wp-includes/post-template.php */
2550 $text = apply_filters( 'the_content', $text );
2551 $text = str_replace(']]>', ']]>', $text);
2554 * Filter the number of words in an excerpt.
2558 * @param int $number The number of words. Default 55.
2560 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2562 * Filter the string in the "more" link displayed after a trimmed excerpt.
2566 * @param string $more_string The string shown within the more link.
2568 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2569 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2572 * Filter the trimmed excerpt string.
2576 * @param string $text The trimmed text.
2577 * @param string $raw_excerpt The text prior to trimming.
2579 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2583 * Trims text to a certain number of words.
2585 * This function is localized. For languages that count 'words' by the individual
2586 * character (such as East Asian languages), the $num_words argument will apply
2587 * to the number of individual characters.
2591 * @param string $text Text to trim.
2592 * @param int $num_words Number of words. Default 55.
2593 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2594 * @return string Trimmed text.
2596 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2597 if ( null === $more )
2598 $more = __( '…' );
2599 $original_text = $text;
2600 $text = wp_strip_all_tags( $text );
2601 /* translators: If your word count is based on single characters (East Asian characters),
2602 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2603 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2604 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2605 preg_match_all( '/./u', $text, $words_array );
2606 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2609 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2612 if ( count( $words_array ) > $num_words ) {
2613 array_pop( $words_array );
2614 $text = implode( $sep, $words_array );
2615 $text = $text . $more;
2617 $text = implode( $sep, $words_array );
2620 * Filter the text content after words have been trimmed.
2624 * @param string $text The trimmed text.
2625 * @param int $num_words The number of words to trim the text to. Default 5.
2626 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2627 * @param string $original_text The text before it was trimmed.
2629 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2633 * Converts named entities into numbered entities.
2637 * @param string $text The text within which entities will be converted.
2638 * @return string Text with converted entities.
2640 function ent2ncr($text) {
2643 * Filter text before named entities are converted into numbered entities.
2645 * A non-null string must be returned for the filter to be evaluated.
2649 * @param null $converted_text The text to be converted. Default null.
2650 * @param string $text The text prior to entity conversion.
2652 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2653 if( null !== $filtered )
2657 '"' => '"',
2662 ' ' => ' ',
2663 '¡' => '¡',
2664 '¢' => '¢',
2665 '£' => '£',
2666 '¤' => '¤',
2667 '¥' => '¥',
2668 '¦' => '¦',
2669 '&brkbar;' => '¦',
2670 '§' => '§',
2671 '¨' => '¨',
2672 '¨' => '¨',
2673 '©' => '©',
2674 'ª' => 'ª',
2675 '«' => '«',
2676 '¬' => '¬',
2677 '­' => '­',
2678 '®' => '®',
2679 '¯' => '¯',
2680 '&hibar;' => '¯',
2681 '°' => '°',
2682 '±' => '±',
2683 '²' => '²',
2684 '³' => '³',
2685 '´' => '´',
2686 'µ' => 'µ',
2687 '¶' => '¶',
2688 '·' => '·',
2689 '¸' => '¸',
2690 '¹' => '¹',
2691 'º' => 'º',
2692 '»' => '»',
2693 '¼' => '¼',
2694 '½' => '½',
2695 '¾' => '¾',
2696 '¿' => '¿',
2697 'À' => 'À',
2698 'Á' => 'Á',
2699 'Â' => 'Â',
2700 'Ã' => 'Ã',
2701 'Ä' => 'Ä',
2702 'Å' => 'Å',
2703 'Æ' => 'Æ',
2704 'Ç' => 'Ç',
2705 'È' => 'È',
2706 'É' => 'É',
2707 'Ê' => 'Ê',
2708 'Ë' => 'Ë',
2709 'Ì' => 'Ì',
2710 'Í' => 'Í',
2711 'Î' => 'Î',
2712 'Ï' => 'Ï',
2713 'Ð' => 'Ð',
2714 'Ñ' => 'Ñ',
2715 'Ò' => 'Ò',
2716 'Ó' => 'Ó',
2717 'Ô' => 'Ô',
2718 'Õ' => 'Õ',
2719 'Ö' => 'Ö',
2720 '×' => '×',
2721 'Ø' => 'Ø',
2722 'Ù' => 'Ù',
2723 'Ú' => 'Ú',
2724 'Û' => 'Û',
2725 'Ü' => 'Ü',
2726 'Ý' => 'Ý',
2727 'Þ' => 'Þ',
2728 'ß' => 'ß',
2729 'à' => 'à',
2730 'á' => 'á',
2731 'â' => 'â',
2732 'ã' => 'ã',
2733 'ä' => 'ä',
2734 'å' => 'å',
2735 'æ' => 'æ',
2736 'ç' => 'ç',
2737 'è' => 'è',
2738 'é' => 'é',
2739 'ê' => 'ê',
2740 'ë' => 'ë',
2741 'ì' => 'ì',
2742 'í' => 'í',
2743 'î' => 'î',
2744 'ï' => 'ï',
2745 'ð' => 'ð',
2746 'ñ' => 'ñ',
2747 'ò' => 'ò',
2748 'ó' => 'ó',
2749 'ô' => 'ô',
2750 'õ' => 'õ',
2751 'ö' => 'ö',
2752 '÷' => '÷',
2753 'ø' => 'ø',
2754 'ù' => 'ù',
2755 'ú' => 'ú',
2756 'û' => 'û',
2757 'ü' => 'ü',
2758 'ý' => 'ý',
2759 'þ' => 'þ',
2760 'ÿ' => 'ÿ',
2761 'Œ' => 'Œ',
2762 'œ' => 'œ',
2763 'Š' => 'Š',
2764 'š' => 'š',
2765 'Ÿ' => 'Ÿ',
2766 'ƒ' => 'ƒ',
2767 'ˆ' => 'ˆ',
2768 '˜' => '˜',
2769 'Α' => 'Α',
2770 'Β' => 'Β',
2771 'Γ' => 'Γ',
2772 'Δ' => 'Δ',
2773 'Ε' => 'Ε',
2774 'Ζ' => 'Ζ',
2775 'Η' => 'Η',
2776 'Θ' => 'Θ',
2777 'Ι' => 'Ι',
2778 'Κ' => 'Κ',
2779 'Λ' => 'Λ',
2783 'Ο' => 'Ο',
2785 'Ρ' => 'Ρ',
2786 'Σ' => 'Σ',
2787 'Τ' => 'Τ',
2788 'Υ' => 'Υ',
2789 'Φ' => 'Φ',
2790 'Χ' => 'Χ',
2791 'Ψ' => 'Ψ',
2792 'Ω' => 'Ω',
2793 'α' => 'α',
2794 'β' => 'β',
2795 'γ' => 'γ',
2796 'δ' => 'δ',
2797 'ε' => 'ε',
2798 'ζ' => 'ζ',
2799 'η' => 'η',
2800 'θ' => 'θ',
2801 'ι' => 'ι',
2802 'κ' => 'κ',
2803 'λ' => 'λ',
2807 'ο' => 'ο',
2809 'ρ' => 'ρ',
2810 'ς' => 'ς',
2811 'σ' => 'σ',
2812 'τ' => 'τ',
2813 'υ' => 'υ',
2814 'φ' => 'φ',
2815 'χ' => 'χ',
2816 'ψ' => 'ψ',
2817 'ω' => 'ω',
2818 'ϑ' => 'ϑ',
2819 'ϒ' => 'ϒ',
2820 'ϖ' => 'ϖ',
2821 ' ' => ' ',
2822 ' ' => ' ',
2823 ' ' => ' ',
2824 '‌' => '‌',
2825 '‍' => '‍',
2826 '‎' => '‎',
2827 '‏' => '‏',
2828 '–' => '–',
2829 '—' => '—',
2830 '‘' => '‘',
2831 '’' => '’',
2832 '‚' => '‚',
2833 '“' => '“',
2834 '”' => '”',
2835 '„' => '„',
2836 '†' => '†',
2837 '‡' => '‡',
2838 '•' => '•',
2839 '…' => '…',
2840 '‰' => '‰',
2841 '′' => '′',
2842 '″' => '″',
2843 '‹' => '‹',
2844 '›' => '›',
2845 '‾' => '‾',
2846 '⁄' => '⁄',
2847 '€' => '€',
2848 'ℑ' => 'ℑ',
2849 '℘' => '℘',
2850 'ℜ' => 'ℜ',
2851 '™' => '™',
2852 'ℵ' => 'ℵ',
2853 '↵' => '↵',
2854 '⇐' => '⇐',
2855 '⇑' => '⇑',
2856 '⇒' => '⇒',
2857 '⇓' => '⇓',
2858 '⇔' => '⇔',
2859 '∀' => '∀',
2860 '∂' => '∂',
2861 '∃' => '∃',
2862 '∅' => '∅',
2863 '∇' => '∇',
2864 '∈' => '∈',
2865 '∉' => '∉',
2866 '∋' => '∋',
2867 '∏' => '∏',
2868 '∑' => '∑',
2869 '−' => '−',
2870 '∗' => '∗',
2871 '√' => '√',
2872 '∝' => '∝',
2873 '∞' => '∞',
2874 '∠' => '∠',
2875 '∧' => '∧',
2876 '∨' => '∨',
2877 '∩' => '∩',
2878 '∪' => '∪',
2879 '∫' => '∫',
2880 '∴' => '∴',
2881 '∼' => '∼',
2882 '≅' => '≅',
2883 '≈' => '≈',
2884 '≠' => '≠',
2885 '≡' => '≡',
2886 '≤' => '≤',
2887 '≥' => '≥',
2888 '⊂' => '⊂',
2889 '⊃' => '⊃',
2890 '⊄' => '⊄',
2891 '⊆' => '⊆',
2892 '⊇' => '⊇',
2893 '⊕' => '⊕',
2894 '⊗' => '⊗',
2895 '⊥' => '⊥',
2896 '⋅' => '⋅',
2897 '⌈' => '⌈',
2898 '⌉' => '⌉',
2899 '⌊' => '⌊',
2900 '⌋' => '⌋',
2901 '⟨' => '〈',
2902 '⟩' => '〉',
2903 '←' => '←',
2904 '↑' => '↑',
2905 '→' => '→',
2906 '↓' => '↓',
2907 '↔' => '↔',
2908 '◊' => '◊',
2909 '♠' => '♠',
2910 '♣' => '♣',
2911 '♥' => '♥',
2912 '♦' => '♦'
2915 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2919 * Formats text for the rich text editor.
2921 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2922 * be applied to an empty string.
2926 * @param string $text The text to be formatted.
2927 * @return string The formatted text after filter is applied.
2929 function wp_richedit_pre($text) {
2930 if ( empty( $text ) ) {
2932 * Filter text returned for the rich text editor.
2934 * This filter is first evaluated, and the value returned, if an empty string
2935 * is passed to wp_richedit_pre(). If an empty string is passed, it results
2936 * in a break tag and line feed.
2938 * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
2939 * return after being formatted.
2943 * @param string $output Text for the rich text editor.
2945 return apply_filters( 'richedit_pre', '' );
2948 $output = convert_chars($text);
2949 $output = wpautop($output);
2950 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
2952 /** This filter is documented in wp-includes/formatting.php */
2953 return apply_filters( 'richedit_pre', $output );
2957 * Formats text for the HTML editor.
2959 * Unless $output is empty it will pass through htmlspecialchars before the
2960 * 'htmledit_pre' filter is applied.
2964 * @param string $output The text to be formatted.
2965 * @return string Formatted text after filter applied.
2967 function wp_htmledit_pre($output) {
2968 if ( !empty($output) )
2969 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
2972 * Filter the text before it is formatted for the HTML editor.
2976 * @param string $output The HTML-formatted text.
2978 return apply_filters( 'htmledit_pre', $output );
2982 * Perform a deep string replace operation to ensure the values in $search are no longer present
2984 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2985 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2986 * str_replace would return
2991 * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
2992 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
2993 * @return string The string with the replaced svalues.
2995 function _deep_replace( $search, $subject ) {
2996 $subject = (string) $subject;
3000 $subject = str_replace( $search, '', $subject, $count );
3007 * Escapes data for use in a MySQL query.
3009 * Usually you should prepare queries using wpdb::prepare().
3010 * Sometimes, spot-escaping is required or useful. One example
3011 * is preparing an array for use in an IN clause.
3014 * @param string|array $data Unescaped data
3015 * @return string|array Escaped data
3017 function esc_sql( $data ) {
3019 return $wpdb->_escape( $data );
3023 * Checks and cleans a URL.
3025 * A number of characters are removed from the URL. If the URL is for displaying
3026 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3027 * is applied to the returned cleaned URL.
3031 * @param string $url The URL to be cleaned.
3032 * @param array $protocols Optional. An array of acceptable protocols.
3033 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
3034 * @param string $_context Private. Use esc_url_raw() for database usage.
3035 * @return string The cleaned $url after the 'clean_url' filter is applied.
3037 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3038 $original_url = $url;
3042 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3043 $strip = array('%0d', '%0a', '%0D', '%0A');
3044 $url = _deep_replace($strip, $url);
3045 $url = str_replace(';//', '://', $url);
3046 /* If the URL doesn't appear to contain a scheme, we
3047 * presume it needs http:// appended (unless a relative
3048 * link starting with /, # or ? or a php file).
3050 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3051 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3052 $url = 'http://' . $url;
3054 // Replace ampersands and single quotes only when displaying.
3055 if ( 'display' == $_context ) {
3056 $url = wp_kses_normalize_entities( $url );
3057 $url = str_replace( '&', '&', $url );
3058 $url = str_replace( "'", ''', $url );
3061 if ( '/' === $url[0] ) {
3062 $good_protocol_url = $url;
3064 if ( ! is_array( $protocols ) )
3065 $protocols = wp_allowed_protocols();
3066 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3067 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3072 * Filter a string cleaned and escaped for output as a URL.
3076 * @param string $good_protocol_url The cleaned URL to be returned.
3077 * @param string $original_url The URL prior to cleaning.
3078 * @param string $_context If 'display', replace ampersands and single quotes only.
3080 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3084 * Performs esc_url() for database usage.
3088 * @param string $url The URL to be cleaned.
3089 * @param array $protocols An array of acceptable protocols.
3090 * @return string The cleaned URL.
3092 function esc_url_raw( $url, $protocols = null ) {
3093 return esc_url( $url, $protocols, 'db' );
3097 * Convert entities, while preserving already-encoded entities.
3099 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3103 * @param string $myHTML The text to be converted.
3104 * @return string Converted text.
3106 function htmlentities2($myHTML) {
3107 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3108 $translation_table[chr(38)] = '&';
3109 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3113 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3115 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3116 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3117 * be in single quotes. The filter 'js_escape' is also applied here.
3121 * @param string $text The text to be escaped.
3122 * @return string Escaped text.
3124 function esc_js( $text ) {
3125 $safe_text = wp_check_invalid_utf8( $text );
3126 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3127 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3128 $safe_text = str_replace( "\r", '', $safe_text );
3129 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3131 * Filter a string cleaned and escaped for output in JavaScript.
3133 * Text passed to esc_js() is stripped of invalid or special characters,
3134 * and properly slashed for output.
3138 * @param string $safe_text The text after it has been escaped.
3139 * @param string $text The text prior to being escaped.
3141 return apply_filters( 'js_escape', $safe_text, $text );
3145 * Escaping for HTML blocks.
3149 * @param string $text
3152 function esc_html( $text ) {
3153 $safe_text = wp_check_invalid_utf8( $text );
3154 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3156 * Filter a string cleaned and escaped for output in HTML.
3158 * Text passed to esc_html() is stripped of invalid or special characters
3163 * @param string $safe_text The text after it has been escaped.
3164 * @param string $text The text prior to being escaped.
3166 return apply_filters( 'esc_html', $safe_text, $text );
3170 * Escaping for HTML attributes.
3174 * @param string $text
3177 function esc_attr( $text ) {
3178 $safe_text = wp_check_invalid_utf8( $text );
3179 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3181 * Filter a string cleaned and escaped for output in an HTML attribute.
3183 * Text passed to esc_attr() is stripped of invalid or special characters
3188 * @param string $safe_text The text after it has been escaped.
3189 * @param string $text The text prior to being escaped.
3191 return apply_filters( 'attribute_escape', $safe_text, $text );
3195 * Escaping for textarea values.
3199 * @param string $text
3202 function esc_textarea( $text ) {
3203 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3205 * Filter a string cleaned and escaped for output in a textarea element.
3209 * @param string $safe_text The text after it has been escaped.
3210 * @param string $text The text prior to being escaped.
3212 return apply_filters( 'esc_textarea', $safe_text, $text );
3216 * Escape an HTML tag name.
3220 * @param string $tag_name
3223 function tag_escape($tag_name) {
3224 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3226 * Filter a string cleaned and escaped for output as an HTML tag.
3230 * @param string $safe_tag The tag name after it has been escaped.
3231 * @param string $tag_name The text before it was escaped.
3233 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3237 * Convert full URL paths to absolute paths.
3239 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3240 * beginning, so it isn't a true relative link, but from the web root base.
3243 * @since 4.1.0 Support was added for relative URLs.
3245 * @param string $link Full URL path.
3246 * @return string Absolute path.
3248 function wp_make_link_relative( $link ) {
3249 return preg_replace( '|^(https?:)?//[^/]+(/.*)|i', '$2', $link );
3253 * Sanitises various option values based on the nature of the option.
3255 * This is basically a switch statement which will pass $value through a number
3256 * of functions depending on the $option.
3260 * @param string $option The name of the option.
3261 * @param string $value The unsanitised value.
3262 * @return string Sanitized value.
3264 function sanitize_option($option, $value) {
3266 switch ( $option ) {
3267 case 'admin_email' :
3268 case 'new_admin_email' :
3269 $value = sanitize_email( $value );
3270 if ( ! is_email( $value ) ) {
3271 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3272 if ( function_exists( 'add_settings_error' ) )
3273 add_settings_error( $option, 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) );
3277 case 'thumbnail_size_w':
3278 case 'thumbnail_size_h':
3279 case 'medium_size_w':
3280 case 'medium_size_h':
3281 case 'large_size_w':
3282 case 'large_size_h':
3283 case 'mailserver_port':
3284 case 'comment_max_links':
3285 case 'page_on_front':
3286 case 'page_for_posts':
3287 case 'rss_excerpt_length':
3288 case 'default_category':
3289 case 'default_email_category':
3290 case 'default_link_category':
3291 case 'close_comments_days_old':
3292 case 'comments_per_page':
3293 case 'thread_comments_depth':
3294 case 'users_can_register':
3295 case 'start_of_week':
3296 $value = absint( $value );
3299 case 'posts_per_page':
3300 case 'posts_per_rss':
3301 $value = (int) $value;
3302 if ( empty($value) )
3305 $value = abs($value);
3308 case 'default_ping_status':
3309 case 'default_comment_status':
3310 // Options that if not there have 0 value but need to be something like "closed"
3311 if ( $value == '0' || $value == '')
3315 case 'blogdescription':
3317 $value = wp_kses_post( $value );
3318 $value = esc_html( $value );
3321 case 'blog_charset':
3322 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3326 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3327 if ( null === $value )
3330 $value = intval( $value );
3335 case 'mailserver_url':
3336 case 'mailserver_login':
3337 case 'mailserver_pass':
3339 $value = strip_tags( $value );
3340 $value = wp_kses_data( $value );
3344 $value = explode( "\n", $value );
3345 $value = array_filter( array_map( 'trim', $value ) );
3346 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3347 $value = implode( "\n", $value );
3351 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3355 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3356 $value = esc_url_raw($value);
3358 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3359 if ( function_exists('add_settings_error') )
3360 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3365 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3366 $value = esc_url_raw($value);
3368 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3369 if ( function_exists('add_settings_error') )
3370 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3375 $allowed = get_available_languages();
3376 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3377 $allowed[] = WPLANG;
3379 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3380 $value = get_option( $option );
3384 case 'illegal_names':
3385 if ( ! is_array( $value ) )
3386 $value = explode( ' ', $value );
3388 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3394 case 'limited_email_domains':
3395 case 'banned_email_domains':
3396 if ( ! is_array( $value ) )
3397 $value = explode( "\n", $value );
3399 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3402 foreach ( $domains as $domain ) {
3403 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
3410 case 'timezone_string':
3411 $allowed_zones = timezone_identifiers_list();
3412 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3413 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3414 if ( function_exists('add_settings_error') )
3415 add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
3419 case 'permalink_structure':
3420 case 'category_base':
3422 $value = esc_url_raw( $value );
3423 $value = str_replace( 'http://', '', $value );
3426 case 'default_role' :
3427 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3428 $value = 'subscriber';
3431 case 'moderation_keys':
3432 case 'blacklist_keys':
3433 $value = explode( "\n", $value );
3434 $value = array_filter( array_map( 'trim', $value ) );
3435 $value = array_unique( $value );
3436 $value = implode( "\n", $value );
3441 * Filter an option value following sanitization.
3445 * @param string $value The sanitized option value.
3446 * @param string $option The option name.
3448 $value = apply_filters( "sanitize_option_{$option}", $value, $option );
3454 * Parses a string into variables to be stored in an array.
3456 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3457 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3461 * @param string $string The string to be parsed.
3462 * @param array $array Variables will be stored in this array.
3464 function wp_parse_str( $string, &$array ) {
3465 parse_str( $string, $array );
3466 if ( get_magic_quotes_gpc() )
3467 $array = stripslashes_deep( $array );
3469 * Filter the array of variables derived from a parsed string.
3473 * @param array $array The array populated with variables.
3475 $array = apply_filters( 'wp_parse_str', $array );
3479 * Convert lone less than signs.
3481 * KSES already converts lone greater than signs.
3485 * @param string $text Text to be converted.
3486 * @return string Converted text.
3488 function wp_pre_kses_less_than( $text ) {
3489 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3493 * Callback function used by preg_replace.
3497 * @param array $matches Populated by matches to preg_replace.
3498 * @return string The text returned after esc_html if needed.
3500 function wp_pre_kses_less_than_callback( $matches ) {
3501 if ( false === strpos($matches[0], '>') )
3502 return esc_html($matches[0]);
3507 * WordPress implementation of PHP sprintf() with filters.
3510 * @link http://www.php.net/sprintf
3512 * @param string $pattern The string which formatted args are inserted.
3513 * @param mixed $args,... Arguments to be formatted into the $pattern string.
3514 * @return string The formatted string.
3516 function wp_sprintf( $pattern ) {
3517 $args = func_get_args();
3518 $len = strlen($pattern);
3522 while ( $len > $start ) {
3523 // Last character: append and break
3524 if ( strlen($pattern) - 1 == $start ) {
3525 $result .= substr($pattern, -1);
3529 // Literal %: append and continue
3530 if ( substr($pattern, $start, 2) == '%%' ) {
3536 // Get fragment before next %
3537 $end = strpos($pattern, '%', $start + 1);
3538 if ( false === $end )
3540 $fragment = substr($pattern, $start, $end - $start);
3542 // Fragment has a specifier
3543 if ( $pattern[$start] == '%' ) {
3544 // Find numbered arguments or take the next one in order
3545 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3546 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3547 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3550 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3554 * Filter a fragment from the pattern passed to wp_sprintf().
3556 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3560 * @param string $fragment A fragment from the pattern.
3561 * @param string $arg The argument.
3563 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3564 if ( $_fragment != $fragment )
3565 $fragment = $_fragment;
3567 $fragment = sprintf($fragment, strval($arg) );
3570 // Append to result and move to next fragment
3571 $result .= $fragment;
3578 * Localize list items before the rest of the content.
3580 * The '%l' must be at the first characters can then contain the rest of the
3581 * content. The list items will have ', ', ', and', and ' and ' added depending
3582 * on the amount of list items in the $args parameter.
3586 * @param string $pattern Content containing '%l' at the beginning.
3587 * @param array $args List items to prepend to the content and replace '%l'.
3588 * @return string Localized list items and rest of the content.
3590 function wp_sprintf_l($pattern, $args) {
3592 if ( substr($pattern, 0, 2) != '%l' )
3595 // Nothing to work with
3600 * Filter the translated delimiters used by wp_sprintf_l().
3601 * Placeholders (%s) are included to assist translators and then
3602 * removed before the array of strings reaches the filter.
3604 * Please note: Ampersands and entities should be avoided here.
3608 * @param array $delimiters An array of translated delimiters.
3610 $l = apply_filters( 'wp_sprintf_l', array(
3611 /* translators: used to join items in a list with more than 2 items */
3612 'between' => sprintf( __('%s, %s'), '', '' ),
3613 /* translators: used to join last two items in a list with more than 2 times */
3614 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3615 /* translators: used to join items in a list with only 2 items */
3616 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3619 $args = (array) $args;
3620 $result = array_shift($args);
3621 if ( count($args) == 1 )
3622 $result .= $l['between_only_two'] . array_shift($args);
3623 // Loop when more than two args
3626 $arg = array_shift($args);
3629 $result .= $l['between_last_two'] . $arg;
3631 $result .= $l['between'] . $arg;
3633 return $result . substr($pattern, 2);
3637 * Safely extracts not more than the first $count characters from html string.
3639 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3640 * be counted as one character. For example & will be counted as 4, < as
3645 * @param string $str String to get the excerpt from.
3646 * @param integer $count Maximum number of characters to take.
3647 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3648 * @return string The excerpt.
3650 function wp_html_excerpt( $str, $count, $more = null ) {
3651 if ( null === $more )
3653 $str = wp_strip_all_tags( $str, true );
3654 $excerpt = mb_substr( $str, 0, $count );
3655 // remove part of an entity at the end
3656 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3657 if ( $str != $excerpt )
3658 $excerpt = trim( $excerpt ) . $more;
3663 * Add a Base url to relative links in passed content.
3665 * By default it supports the 'src' and 'href' attributes. However this can be
3666 * changed via the 3rd param.
3670 * @param string $content String to search for links in.
3671 * @param string $base The base URL to prefix to links.
3672 * @param array $attrs The attributes which should be processed.
3673 * @return string The processed content.
3675 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3676 global $_links_add_base;
3677 $_links_add_base = $base;
3678 $attrs = implode('|', (array)$attrs);
3679 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3683 * Callback to add a base url to relative links in passed content.
3688 * @param string $m The matched link.
3689 * @return string The processed link.
3691 function _links_add_base($m) {
3692 global $_links_add_base;
3693 //1 = attribute name 2 = quotation mark 3 = URL
3694 return $m[1] . '=' . $m[2] .
3695 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3697 WP_HTTP::make_absolute_url( $m[3], $_links_add_base )
3703 * Adds a Target attribute to all links in passed content.
3705 * This function by default only applies to `<a>` tags, however this can be
3706 * modified by the 3rd param.
3708 * *NOTE:* Any current target attributed will be stripped and replaced.
3712 * @param string $content String to search for links in.
3713 * @param string $target The Target to add to the links.
3714 * @param array $tags An array of tags to apply to.
3715 * @return string The processed content.
3717 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3718 global $_links_add_target;
3719 $_links_add_target = $target;
3720 $tags = implode('|', (array)$tags);
3721 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
3725 * Callback to add a target attribute to all links in passed content.
3730 * @param string $m The matched link.
3731 * @return string The processed link.
3733 function _links_add_target( $m ) {
3734 global $_links_add_target;
3736 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
3737 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3741 * Normalize EOL characters and strip duplicate whitespace.
3745 * @param string $str The string to normalize.
3746 * @return string The normalized string.
3748 function normalize_whitespace( $str ) {
3749 $str = trim( $str );
3750 $str = str_replace( "\r", "\n", $str );
3751 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3756 * Properly strip all HTML tags including script and style
3758 * This differs from strip_tags() because it removes the contents of
3759 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
3760 * will return 'something'. wp_strip_all_tags will return ''
3764 * @param string $string String containing HTML tags
3765 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3766 * @return string The processed string.
3768 function wp_strip_all_tags($string, $remove_breaks = false) {
3769 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3770 $string = strip_tags($string);
3772 if ( $remove_breaks )
3773 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3775 return trim( $string );
3779 * Sanitize a string from user input or from the db
3781 * check for invalid UTF-8,
3782 * Convert single < characters to entity,
3784 * remove line breaks, tabs and extra white space,
3789 * @param string $str
3792 function sanitize_text_field($str) {
3793 $filtered = wp_check_invalid_utf8( $str );
3795 if ( strpos($filtered, '<') !== false ) {
3796 $filtered = wp_pre_kses_less_than( $filtered );
3797 // This will strip extra whitespace for us.
3798 $filtered = wp_strip_all_tags( $filtered, true );
3800 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
3804 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
3805 $filtered = str_replace($match[0], '', $filtered);
3810 // Strip out the whitespace that may now exist after removing the octets.
3811 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
3815 * Filter a sanitized text field string.
3819 * @param string $filtered The sanitized string.
3820 * @param string $str The string prior to being sanitized.
3822 return apply_filters( 'sanitize_text_field', $filtered, $str );
3826 * i18n friendly version of basename()
3830 * @param string $path A path.
3831 * @param string $suffix If the filename ends in suffix this will also be cut off.
3834 function wp_basename( $path, $suffix = '' ) {
3835 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
3839 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
3841 * Violating our coding standards for a good function name.
3845 function capital_P_dangit( $text ) {
3846 // Simple replacement for titles
3847 $current_filter = current_filter();
3848 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
3849 return str_replace( 'Wordpress', 'WordPress', $text );
3850 // Still here? Use the more judicious replacement
3851 static $dblq = false;
3852 if ( false === $dblq )
3853 $dblq = _x( '“', 'opening curly double quote' );
3855 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
3856 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
3862 * Sanitize a mime type
3866 * @param string $mime_type Mime type
3867 * @return string Sanitized mime type
3869 function sanitize_mime_type( $mime_type ) {
3870 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3872 * Filter a mime type following sanitization.
3876 * @param string $sani_mime_type The sanitized mime type.
3877 * @param string $mime_type The mime type prior to sanitization.
3879 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
3883 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
3887 * @param string $to_ping Space or carriage return separated URLs
3888 * @return string URLs starting with the http or https protocol, separated by a carriage return.
3890 function sanitize_trackback_urls( $to_ping ) {
3891 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
3892 foreach ( $urls_to_ping as $k => $url ) {
3893 if ( !preg_match( '#^https?://.#i', $url ) )
3894 unset( $urls_to_ping[$k] );
3896 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
3897 $urls_to_ping = implode( "\n", $urls_to_ping );
3899 * Filter a list of trackback URLs following sanitization.
3901 * The string returned here consists of a space or carriage return-delimited list
3902 * of trackback URLs.
3906 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
3907 * @param string $to_ping Space or carriage return separated URLs before sanitization.
3909 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
3913 * Add slashes to a string or array of strings.
3915 * This should be used when preparing data for core API that expects slashed data.
3916 * This should not be used to escape data going directly into an SQL query.
3920 * @param string|array $value String or array of strings to slash.
3921 * @return string|array Slashed $value
3923 function wp_slash( $value ) {
3924 if ( is_array( $value ) ) {
3925 foreach ( $value as $k => $v ) {
3926 if ( is_array( $v ) ) {
3927 $value[$k] = wp_slash( $v );
3929 $value[$k] = addslashes( $v );
3933 $value = addslashes( $value );
3940 * Remove slashes from a string or array of strings.
3942 * This should be used to remove slashes from data passed to core API that
3943 * expects data to be unslashed.
3947 * @param string|array $value String or array of strings to unslash.
3948 * @return string|array Unslashed $value
3950 function wp_unslash( $value ) {
3951 return stripslashes_deep( $value );
3955 * Extract and return the first URL from passed content.
3959 * @param string $content A string which might contain a URL.
3960 * @return string The found URL.
3962 function get_url_in_content( $content ) {
3963 if ( empty( $content ) ) {
3967 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
3968 return esc_url_raw( $matches[2] );
3975 * Returns the regexp for common whitespace characters.
3977 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
3978 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
3979 * sequence was found to be unreliable due to random inclusion of the A0 byte.
3983 * @return string The spaces regexp.
3985 function wp_spaces_regexp() {
3988 if ( empty( $spaces ) ) {
3990 * Filter the regexp for common whitespace characters.
3992 * This string is substituted for the \s sequence as needed in regular
3993 * expressions. For websites not written in English, different characters
3994 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
3995 * sequence may not be in use.
3999 * @param string $spaces Regexp pattern for matching common whitespace characters.
4001 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );