[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> formatting.php (source)

   1  <?php
   2  /**
   3   * Main WordPress Formatting API.
   4   *
   5   * Handles many functions for formatting output.
   6   *
   7   * @package WordPress
   8   */
   9  
  10  /**
  11   * Replaces common plain text characters with formatted entities.
  12   *
  13   * Returns given text with transformations of quotes into smart quotes, apostrophes,
  14   * dashes, ellipses, the trademark symbol, and the multiplication symbol.
  15   *
  16   * As an example,
  17   *
  18   *     'cause today's effort makes it worth tomorrow's "holiday" ...
  19   *
  20   * Becomes:
  21   *
  22   *     &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221; &#8230;
  23   *
  24   * Code within certain HTML blocks are skipped.
  25   *
  26   * Do not use this function before the {@see 'init'} action hook; everything will break.
  27   *
  28   * @since 0.71
  29   *
  30   * @global array $wp_cockneyreplace Array of formatted entities for certain common phrases.
  31   * @global array $shortcode_tags
  32   * @staticvar array  $static_characters
  33   * @staticvar array  $static_replacements
  34   * @staticvar array  $dynamic_characters
  35   * @staticvar array  $dynamic_replacements
  36   * @staticvar array  $default_no_texturize_tags
  37   * @staticvar array  $default_no_texturize_shortcodes
  38   * @staticvar bool   $run_texturize
  39   * @staticvar string $apos
  40   * @staticvar string $prime
  41   * @staticvar string $double_prime
  42   * @staticvar string $opening_quote
  43   * @staticvar string $closing_quote
  44   * @staticvar string $opening_single_quote
  45   * @staticvar string $closing_single_quote
  46   * @staticvar string $open_q_flag
  47   * @staticvar string $open_sq_flag
  48   * @staticvar string $apos_flag
  49   *
  50   * @param string $text  The text to be formatted.
  51   * @param bool   $reset Set to true for unit testing. Translated patterns will reset.
  52   * @return string The string replaced with HTML entities.
  53   */
  54  function wptexturize( $text, $reset = false ) {
  55      global $wp_cockneyreplace, $shortcode_tags;
  56      static $static_characters            = null,
  57          $static_replacements             = null,
  58          $dynamic_characters              = null,
  59          $dynamic_replacements            = null,
  60          $default_no_texturize_tags       = null,
  61          $default_no_texturize_shortcodes = null,
  62          $run_texturize                   = true,
  63          $apos                            = null,
  64          $prime                           = null,
  65          $double_prime                    = null,
  66          $opening_quote                   = null,
  67          $closing_quote                   = null,
  68          $opening_single_quote            = null,
  69          $closing_single_quote            = null,
  70          $open_q_flag                     = '<!--oq-->',
  71          $open_sq_flag                    = '<!--osq-->',
  72          $apos_flag                       = '<!--apos-->';
  73  
  74      // If there's nothing to do, just stop.
  75      if ( empty( $text ) || false === $run_texturize ) {
  76          return $text;
  77      }
  78  
  79      // Set up static variables. Run once only.
  80      if ( $reset || ! isset( $static_characters ) ) {
  81          /**
  82           * Filters whether to skip running wptexturize().
  83           *
  84           * Passing false to the filter will effectively short-circuit wptexturize().
  85           * returning the original text passed to the function instead.
  86           *
  87           * The filter runs only once, the first time wptexturize() is called.
  88           *
  89           * @since 4.0.0
  90           *
  91           * @see wptexturize()
  92           *
  93           * @param bool $run_texturize Whether to short-circuit wptexturize().
  94           */
  95          $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
  96          if ( false === $run_texturize ) {
  97              return $text;
  98          }
  99  
 100          /* translators: Opening curly double quote. */
 101          $opening_quote = _x( '&#8220;', 'opening curly double quote' );
 102          /* translators: Closing curly double quote. */
 103          $closing_quote = _x( '&#8221;', 'closing curly double quote' );
 104  
 105          /* translators: Apostrophe, for example in 'cause or can't. */
 106          $apos = _x( '&#8217;', 'apostrophe' );
 107  
 108          /* translators: Prime, for example in 9' (nine feet). */
 109          $prime = _x( '&#8242;', 'prime' );
 110          /* translators: Double prime, for example in 9" (nine inches). */
 111          $double_prime = _x( '&#8243;', 'double prime' );
 112  
 113          /* translators: Opening curly single quote. */
 114          $opening_single_quote = _x( '&#8216;', 'opening curly single quote' );
 115          /* translators: Closing curly single quote. */
 116          $closing_single_quote = _x( '&#8217;', 'closing curly single quote' );
 117  
 118          /* translators: En dash. */
 119          $en_dash = _x( '&#8211;', 'en dash' );
 120          /* translators: Em dash. */
 121          $em_dash = _x( '&#8212;', 'em dash' );
 122  
 123          $default_no_texturize_tags       = array( 'pre', 'code', 'kbd', 'style', 'script', 'tt' );
 124          $default_no_texturize_shortcodes = array( 'code' );
 125  
 126          // If a plugin has provided an autocorrect array, use it.
 127          if ( isset( $wp_cockneyreplace ) ) {
 128              $cockney        = array_keys( $wp_cockneyreplace );
 129              $cockneyreplace = array_values( $wp_cockneyreplace );
 130          } else {
 131              /*
 132               * translators: This is a comma-separated list of words that defy the syntax of quotations in normal use,
 133               * for example... 'We do not have enough words yet'... is a typical quoted phrase. But when we write
 134               * lines of code 'til we have enough of 'em, then we need to insert apostrophes instead of quotes.
 135               */
 136              $cockney = explode(
 137                  ',',
 138                  _x(
 139                      "'tain't,'twere,'twas,'tis,'twill,'til,'bout,'nuff,'round,'cause,'em",
 140                      'Comma-separated list of words to texturize in your language'
 141                  )
 142              );
 143  
 144              $cockneyreplace = explode(
 145                  ',',
 146                  _x(
 147                      '&#8217;tain&#8217;t,&#8217;twere,&#8217;twas,&#8217;tis,&#8217;twill,&#8217;til,&#8217;bout,&#8217;nuff,&#8217;round,&#8217;cause,&#8217;em',
 148                      'Comma-separated list of replacement words in your language'
 149                  )
 150              );
 151          }
 152  
 153          $static_characters   = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
 154          $static_replacements = array_merge( array( '&#8230;', $opening_quote, $closing_quote, ' &#8482;' ), $cockneyreplace );
 155  
 156          // Pattern-based replacements of characters.
 157          // Sort the remaining patterns into several arrays for performance tuning.
 158          $dynamic_characters   = array(
 159              'apos'  => array(),
 160              'quote' => array(),
 161              'dash'  => array(),
 162          );
 163          $dynamic_replacements = array(
 164              'apos'  => array(),
 165              'quote' => array(),
 166              'dash'  => array(),
 167          );
 168          $dynamic              = array();
 169          $spaces               = wp_spaces_regexp();
 170  
 171          // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
 172          if ( "'" !== $apos || "'" !== $closing_single_quote ) {
 173              $dynamic[ '/\'(\d\d)\'(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_single_quote;
 174          }
 175          if ( "'" !== $apos || '"' !== $closing_quote ) {
 176              $dynamic[ '/\'(\d\d)"(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_quote;
 177          }
 178  
 179          // '99 '99s '99's (apostrophe)  But never '9 or '99% or '999 or '99.0.
 180          if ( "'" !== $apos ) {
 181              $dynamic['/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/'] = $apos_flag;
 182          }
 183  
 184          // Quoted numbers like '0.42'.
 185          if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
 186              $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $open_sq_flag . '$1' . $closing_single_quote;
 187          }
 188  
 189          // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
 190          if ( "'" !== $opening_single_quote ) {
 191              $dynamic[ '/(?<=\A|[([{"\-]|&lt;|' . $spaces . ')\'/' ] = $open_sq_flag;
 192          }
 193  
 194          // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
 195          if ( "'" !== $apos ) {
 196              $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;!?"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos_flag;
 197          }
 198  
 199          $dynamic_characters['apos']   = array_keys( $dynamic );
 200          $dynamic_replacements['apos'] = array_values( $dynamic );
 201          $dynamic                      = array();
 202  
 203          // Quoted numbers like "42".
 204          if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
 205              $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $open_q_flag . '$1' . $closing_quote;
 206          }
 207  
 208          // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
 209          if ( '"' !== $opening_quote ) {
 210              $dynamic[ '/(?<=\A|[([{\-]|&lt;|' . $spaces . ')"(?!' . $spaces . ')/' ] = $open_q_flag;
 211          }
 212  
 213          $dynamic_characters['quote']   = array_keys( $dynamic );
 214          $dynamic_replacements['quote'] = array_values( $dynamic );
 215          $dynamic                       = array();
 216  
 217          // Dashes and spaces.
 218          $dynamic['/---/'] = $em_dash;
 219          $dynamic[ '/(?<=^|' . $spaces . ')--(?=$|' . $spaces . ')/' ] = $em_dash;
 220          $dynamic['/(?<!xn)--/']                                       = $en_dash;
 221          $dynamic[ '/(?<=^|' . $spaces . ')-(?=$|' . $spaces . ')/' ]  = $en_dash;
 222  
 223          $dynamic_characters['dash']   = array_keys( $dynamic );
 224          $dynamic_replacements['dash'] = array_values( $dynamic );
 225      }
 226  
 227      // Must do this every time in case plugins use these filters in a context sensitive manner.
 228      /**
 229       * Filters the list of HTML elements not to texturize.
 230       *
 231       * @since 2.8.0
 232       *
 233       * @param string[] $default_no_texturize_tags An array of HTML element names.
 234       */
 235      $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
 236      /**
 237       * Filters the list of shortcodes not to texturize.
 238       *
 239       * @since 2.8.0
 240       *
 241       * @param string[] $default_no_texturize_shortcodes An array of shortcode names.
 242       */
 243      $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
 244  
 245      $no_texturize_tags_stack       = array();
 246      $no_texturize_shortcodes_stack = array();
 247  
 248      // Look for shortcodes and HTML elements.
 249  
 250      preg_match_all( '@\[/?([^<>&/\[\]\x00-\x20=]++)@', $text, $matches );
 251      $tagnames         = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
 252      $found_shortcodes = ! empty( $tagnames );
 253      $shortcode_regex  = $found_shortcodes ? _get_wptexturize_shortcode_regex( $tagnames ) : '';
 254      $regex            = _get_wptexturize_split_regex( $shortcode_regex );
 255  
 256      $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
 257  
 258      foreach ( $textarr as &$curl ) {
 259          // Only call _wptexturize_pushpop_element if $curl is a delimiter.
 260          $first = $curl[0];
 261          if ( '<' === $first ) {
 262              if ( '<!--' === substr( $curl, 0, 4 ) ) {
 263                  // This is an HTML comment delimiter.
 264                  continue;
 265              } else {
 266                  // This is an HTML element delimiter.
 267  
 268                  // Replace each & with &#038; unless it already looks like an entity.
 269                  $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
 270  
 271                  _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
 272              }
 273          } elseif ( '' === trim( $curl ) ) {
 274              // This is a newline between delimiters. Performance improves when we check this.
 275              continue;
 276  
 277          } elseif ( '[' === $first && $found_shortcodes && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
 278              // This is a shortcode delimiter.
 279  
 280              if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
 281                  // Looks like a normal shortcode.
 282                  _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
 283              } else {
 284                  // Looks like an escaped shortcode.
 285                  continue;
 286              }
 287          } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
 288              // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
 289  
 290              $curl = str_replace( $static_characters, $static_replacements, $curl );
 291  
 292              if ( false !== strpos( $curl, "'" ) ) {
 293                  $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
 294                  $curl = wptexturize_primes( $curl, "'", $prime, $open_sq_flag, $closing_single_quote );
 295                  $curl = str_replace( $apos_flag, $apos, $curl );
 296                  $curl = str_replace( $open_sq_flag, $opening_single_quote, $curl );
 297              }
 298              if ( false !== strpos( $curl, '"' ) ) {
 299                  $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
 300                  $curl = wptexturize_primes( $curl, '"', $double_prime, $open_q_flag, $closing_quote );
 301                  $curl = str_replace( $open_q_flag, $opening_quote, $curl );
 302              }
 303              if ( false !== strpos( $curl, '-' ) ) {
 304                  $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
 305              }
 306  
 307              // 9x9 (times), but never 0x9999.
 308              if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
 309                  // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
 310                  $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1&#215;$2', $curl );
 311              }
 312  
 313              // Replace each & with &#038; unless it already looks like an entity.
 314              $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
 315          }
 316      }
 317  
 318      return implode( '', $textarr );
 319  }
 320  
 321  /**
 322   * Implements a logic tree to determine whether or not "7'." represents seven feet,
 323   * then converts the special char into either a prime char or a closing quote char.
 324   *
 325   * @since 4.3.0
 326   *
 327   * @param string $haystack    The plain text to be searched.
 328   * @param string $needle      The character to search for such as ' or ".
 329   * @param string $prime       The prime char to use for replacement.
 330   * @param string $open_quote  The opening quote char. Opening quote replacement must be
 331   *                            accomplished already.
 332   * @param string $close_quote The closing quote char to use for replacement.
 333   * @return string The $haystack value after primes and quotes replacements.
 334   */
 335  function wptexturize_primes( $haystack, $needle, $prime, $open_quote, $close_quote ) {
 336      $spaces           = wp_spaces_regexp();
 337      $flag             = '<!--wp-prime-or-quote-->';
 338      $quote_pattern    = "/$needle(?=\\Z|[.,:;!?)}\\-\\]]|&gt;|" . $spaces . ')/';
 339      $prime_pattern    = "/(?<=\\d)$needle/";
 340      $flag_after_digit = "/(?<=\\d)$flag/";
 341      $flag_no_digit    = "/(?<!\\d)$flag/";
 342  
 343      $sentences = explode( $open_quote, $haystack );
 344  
 345      foreach ( $sentences as $key => &$sentence ) {
 346          if ( false === strpos( $sentence, $needle ) ) {
 347              continue;
 348          } elseif ( 0 !== $key && 0 === substr_count( $sentence, $close_quote ) ) {
 349              $sentence = preg_replace( $quote_pattern, $flag, $sentence, -1, $count );
 350              if ( $count > 1 ) {
 351                  // This sentence appears to have multiple closing quotes. Attempt Vulcan logic.
 352                  $sentence = preg_replace( $flag_no_digit, $close_quote, $sentence, -1, $count2 );
 353                  if ( 0 === $count2 ) {
 354                      // Try looking for a quote followed by a period.
 355                      $count2 = substr_count( $sentence, "$flag." );
 356                      if ( $count2 > 0 ) {
 357                          // Assume the rightmost quote-period match is the end of quotation.
 358                          $pos = strrpos( $sentence, "$flag." );
 359                      } else {
 360                          // When all else fails, make the rightmost candidate a closing quote.
 361                          // This is most likely to be problematic in the context of bug #18549.
 362                          $pos = strrpos( $sentence, $flag );
 363                      }
 364                      $sentence = substr_replace( $sentence, $close_quote, $pos, strlen( $flag ) );
 365                  }
 366                  // Use conventional replacement on any remaining primes and quotes.
 367                  $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 368                  $sentence = preg_replace( $flag_after_digit, $prime, $sentence );
 369                  $sentence = str_replace( $flag, $close_quote, $sentence );
 370              } elseif ( 1 == $count ) {
 371                  // Found only one closing quote candidate, so give it priority over primes.
 372                  $sentence = str_replace( $flag, $close_quote, $sentence );
 373                  $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 374              } else {
 375                  // No closing quotes found. Just run primes pattern.
 376                  $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 377              }
 378          } else {
 379              $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 380              $sentence = preg_replace( $quote_pattern, $close_quote, $sentence );
 381          }
 382          if ( '"' == $needle && false !== strpos( $sentence, '"' ) ) {
 383              $sentence = str_replace( '"', $close_quote, $sentence );
 384          }
 385      }
 386  
 387      return implode( $open_quote, $sentences );
 388  }
 389  
 390  /**
 391   * Search for disabled element tags. Push element to stack on tag open and pop
 392   * on tag close.
 393   *
 394   * Assumes first char of $text is tag opening and last char is tag closing.
 395   * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
 396   *
 397   * @since 2.9.0
 398   * @access private
 399   *
 400   * @param string   $text              Text to check. Must be a tag like `<html>` or `[shortcode]`.
 401   * @param string[] $stack             Array of open tag elements.
 402   * @param string[] $disabled_elements Array of tag names to match against. Spaces are not allowed in tag names.
 403   */
 404  function _wptexturize_pushpop_element( $text, &$stack, $disabled_elements ) {
 405      // Is it an opening tag or closing tag?
 406      if ( isset( $text[1] ) && '/' !== $text[1] ) {
 407          $opening_tag = true;
 408          $name_offset = 1;
 409      } elseif ( 0 == count( $stack ) ) {
 410          // Stack is empty. Just stop.
 411          return;
 412      } else {
 413          $opening_tag = false;
 414          $name_offset = 2;
 415      }
 416  
 417      // Parse out the tag name.
 418      $space = strpos( $text, ' ' );
 419      if ( false === $space ) {
 420          $space = -1;
 421      } else {
 422          $space -= $name_offset;
 423      }
 424      $tag = substr( $text, $name_offset, $space );
 425  
 426      // Handle disabled tags.
 427      if ( in_array( $tag, $disabled_elements, true ) ) {
 428          if ( $opening_tag ) {
 429              /*
 430               * This disables texturize until we find a closing tag of our type
 431               * (e.g. <pre>) even if there was invalid nesting before that.
 432               *
 433               * Example: in the case <pre>sadsadasd</code>"baba"</pre>
 434               *          "baba" won't be texturized.
 435               */
 436  
 437              array_push( $stack, $tag );
 438          } elseif ( end( $stack ) == $tag ) {
 439              array_pop( $stack );
 440          }
 441      }
 442  }
 443  
 444  /**
 445   * Replaces double line-breaks with paragraph elements.
 446   *
 447   * A group of regex replaces used to identify text formatted with newlines and
 448   * replace double line-breaks with HTML paragraph tags. The remaining line-breaks
 449   * after conversion become <<br />> tags, unless $br is set to '0' or 'false'.
 450   *
 451   * @since 0.71
 452   *
 453   * @param string $pee The text which has to be formatted.
 454   * @param bool   $br  Optional. If set, this will convert all remaining line-breaks
 455   *                    after paragraphing. Default true.
 456   * @return string Text which has been converted into correct paragraph tags.
 457   */
 458  function wpautop( $pee, $br = true ) {
 459      $pre_tags = array();
 460  
 461      if ( trim( $pee ) === '' ) {
 462          return '';
 463      }
 464  
 465      // Just to make things a little easier, pad the end.
 466      $pee = $pee . "\n";
 467  
 468      /*
 469       * Pre tags shouldn't be touched by autop.
 470       * Replace pre tags with placeholders and bring them back after autop.
 471       */
 472      if ( strpos( $pee, '<pre' ) !== false ) {
 473          $pee_parts = explode( '</pre>', $pee );
 474          $last_pee  = array_pop( $pee_parts );
 475          $pee       = '';
 476          $i         = 0;
 477  
 478          foreach ( $pee_parts as $pee_part ) {
 479              $start = strpos( $pee_part, '<pre' );
 480  
 481              // Malformed HTML?
 482              if ( false === $start ) {
 483                  $pee .= $pee_part;
 484                  continue;
 485              }
 486  
 487              $name              = "<pre wp-pre-tag-$i></pre>";
 488              $pre_tags[ $name ] = substr( $pee_part, $start ) . '</pre>';
 489  
 490              $pee .= substr( $pee_part, 0, $start ) . $name;
 491              $i++;
 492          }
 493  
 494          $pee .= $last_pee;
 495      }
 496      // Change multiple <br>'s into two line breaks, which will turn into paragraphs.
 497      $pee = preg_replace( '|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee );
 498  
 499      $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
 500  
 501      // Add a double line break above block-level opening tags.
 502      $pee = preg_replace( '!(<' . $allblocks . '[\s/>])!', "\n\n$1", $pee );
 503  
 504      // Add a double line break below block-level closing tags.
 505      $pee = preg_replace( '!(</' . $allblocks . '>)!', "$1\n\n", $pee );
 506  
 507      // Add a double line break after hr tags, which are self closing.
 508      $pee = preg_replace( '!(<hr\s*?/?>)!', "$1\n\n", $pee );
 509  
 510      // Standardize newline characters to "\n".
 511      $pee = str_replace( array( "\r\n", "\r" ), "\n", $pee );
 512  
 513      // Find newlines in all elements and add placeholders.
 514      $pee = wp_replace_in_html_tags( $pee, array( "\n" => ' <!-- wpnl --> ' ) );
 515  
 516      // Collapse line breaks before and after <option> elements so they don't get autop'd.
 517      if ( strpos( $pee, '<option' ) !== false ) {
 518          $pee = preg_replace( '|\s*<option|', '<option', $pee );
 519          $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
 520      }
 521  
 522      /*
 523       * Collapse line breaks inside <object> elements, before <param> and <embed> elements
 524       * so they don't get autop'd.
 525       */
 526      if ( strpos( $pee, '</object>' ) !== false ) {
 527          $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
 528          $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
 529          $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
 530      }
 531  
 532      /*
 533       * Collapse line breaks inside <audio> and <video> elements,
 534       * before and after <source> and <track> elements.
 535       */
 536      if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
 537          $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
 538          $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
 539          $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
 540      }
 541  
 542      // Collapse line breaks before and after <figcaption> elements.
 543      if ( strpos( $pee, '<figcaption' ) !== false ) {
 544          $pee = preg_replace( '|\s*(<figcaption[^>]*>)|', '$1', $pee );
 545          $pee = preg_replace( '|</figcaption>\s*|', '</figcaption>', $pee );
 546      }
 547  
 548      // Remove more than two contiguous line breaks.
 549      $pee = preg_replace( "/\n\n+/", "\n\n", $pee );
 550  
 551      // Split up the contents into an array of strings, separated by double line breaks.
 552      $pees = preg_split( '/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY );
 553  
 554      // Reset $pee prior to rebuilding.
 555      $pee = '';
 556  
 557      // Rebuild the content as a string, wrapping every bit with a <p>.
 558      foreach ( $pees as $tinkle ) {
 559          $pee .= '<p>' . trim( $tinkle, "\n" ) . "</p>\n";
 560      }
 561  
 562      // Under certain strange conditions it could create a P of entirely whitespace.
 563      $pee = preg_replace( '|<p>\s*</p>|', '', $pee );
 564  
 565      // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
 566      $pee = preg_replace( '!<p>([^<]+)</(div|address|form)>!', '<p>$1</p></$2>', $pee );
 567  
 568      // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
 569      $pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
 570  
 571      // In some cases <li> may get wrapped in <p>, fix them.
 572      $pee = preg_replace( '|<p>(<li.+?)</p>|', '$1', $pee );
 573  
 574      // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
 575      $pee = preg_replace( '|<p><blockquote([^>]*)>|i', '<blockquote$1><p>', $pee );
 576      $pee = str_replace( '</blockquote></p>', '</p></blockquote>', $pee );
 577  
 578      // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
 579      $pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)!', '$1', $pee );
 580  
 581      // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
 582      $pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
 583  
 584      // Optionally insert line breaks.
 585      if ( $br ) {
 586          // Replace newlines that shouldn't be touched with a placeholder.
 587          $pee = preg_replace_callback( '/<(script|style|svg).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee );
 588  
 589          // Normalize <br>
 590          $pee = str_replace( array( '<br>', '<br/>' ), '<br />', $pee );
 591  
 592          // Replace any new line characters that aren't preceded by a <br /> with a <br />.
 593          $pee = preg_replace( '|(?<!<br />)\s*\n|', "<br />\n", $pee );
 594  
 595          // Replace newline placeholders with newlines.
 596          $pee = str_replace( '<WPPreserveNewline />', "\n", $pee );
 597      }
 598  
 599      // If a <br /> tag is after an opening or closing block tag, remove it.
 600      $pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*<br />!', '$1', $pee );
 601  
 602      // If a <br /> tag is before a subset of opening or closing block tags, remove it.
 603      $pee = preg_replace( '!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee );
 604      $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
 605  
 606      // Replace placeholder <pre> tags with their original content.
 607      if ( ! empty( $pre_tags ) ) {
 608          $pee = str_replace( array_keys( $pre_tags ), array_values( $pre_tags ), $pee );
 609      }
 610  
 611      // Restore newlines in all elements.
 612      if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
 613          $pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
 614      }
 615  
 616      return $pee;
 617  }
 618  
 619  /**
 620   * Separate HTML elements and comments from the text.
 621   *
 622   * @since 4.2.4
 623   *
 624   * @param string $input The text which has to be formatted.
 625   * @return string[] Array of the formatted text.
 626   */
 627  function wp_html_split( $input ) {
 628      return preg_split( get_html_split_regex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE );
 629  }
 630  
 631  /**
 632   * Retrieve the regular expression for an HTML element.
 633   *
 634   * @since 4.4.0
 635   *
 636   * @staticvar string $regex
 637   *
 638   * @return string The regular expression
 639   */
 640  function get_html_split_regex() {
 641      static $regex;
 642  
 643      if ( ! isset( $regex ) ) {
 644          // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 645          $comments =
 646              '!'             // Start of comment, after the <.
 647              . '(?:'         // Unroll the loop: Consume everything until --> is found.
 648              .     '-(?!->)' // Dash not followed by end of comment.
 649              .     '[^\-]*+' // Consume non-dashes.
 650              . ')*+'         // Loop possessively.
 651              . '(?:-->)?';   // End of comment. If not found, match all input.
 652  
 653          $cdata =
 654              '!\[CDATA\['    // Start of comment, after the <.
 655              . '[^\]]*+'     // Consume non-].
 656              . '(?:'         // Unroll the loop: Consume everything until ]]> is found.
 657              .     '](?!]>)' // One ] not followed by end of comment.
 658              .     '[^\]]*+' // Consume non-].
 659              . ')*+'         // Loop possessively.
 660              . '(?:]]>)?';   // End of comment. If not found, match all input.
 661  
 662          $escaped =
 663              '(?='             // Is the element escaped?
 664              .    '!--'
 665              . '|'
 666              .    '!\[CDATA\['
 667              . ')'
 668              . '(?(?=!-)'      // If yes, which type?
 669              .     $comments
 670              . '|'
 671              .     $cdata
 672              . ')';
 673  
 674          $regex =
 675              '/('                // Capture the entire match.
 676              .     '<'           // Find start of element.
 677              .     '(?'          // Conditional expression follows.
 678              .         $escaped  // Find end of escaped element.
 679              .     '|'           // ...else...
 680              .         '[^>]*>?' // Find end of normal element.
 681              .     ')'
 682              . ')/';
 683          // phpcs:enable
 684      }
 685  
 686      return $regex;
 687  }
 688  
 689  /**
 690   * Retrieve the combined regular expression for HTML and shortcodes.
 691   *
 692   * @access private
 693   * @ignore
 694   * @internal This function will be removed in 4.5.0 per Shortcode API Roadmap.
 695   * @since 4.4.0
 696   *
 697   * @staticvar string $html_regex
 698   *
 699   * @param string $shortcode_regex The result from _get_wptexturize_shortcode_regex(). Optional.
 700   * @return string The regular expression
 701   */
 702  function _get_wptexturize_split_regex( $shortcode_regex = '' ) {
 703      static $html_regex;
 704  
 705      if ( ! isset( $html_regex ) ) {
 706          // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 707          $comment_regex =
 708              '!'             // Start of comment, after the <.
 709              . '(?:'         // Unroll the loop: Consume everything until --> is found.
 710              .     '-(?!->)' // Dash not followed by end of comment.
 711              .     '[^\-]*+' // Consume non-dashes.
 712              . ')*+'         // Loop possessively.
 713              . '(?:-->)?';   // End of comment. If not found, match all input.
 714  
 715          $html_regex = // Needs replaced with wp_html_split() per Shortcode API Roadmap.
 716              '<'                  // Find start of element.
 717              . '(?(?=!--)'        // Is this a comment?
 718              .     $comment_regex // Find end of comment.
 719              . '|'
 720              .     '[^>]*>?'      // Find end of element. If not found, match all input.
 721              . ')';
 722          // phpcs:enable
 723      }
 724  
 725      if ( empty( $shortcode_regex ) ) {
 726          $regex = '/(' . $html_regex . ')/';
 727      } else {
 728          $regex = '/(' . $html_regex . '|' . $shortcode_regex . ')/';
 729      }
 730  
 731      return $regex;
 732  }
 733  
 734  /**
 735   * Retrieve the regular expression for shortcodes.
 736   *
 737   * @access private
 738   * @ignore
 739   * @since 4.4.0
 740   *
 741   * @param string[] $tagnames Array of shortcodes to find.
 742   * @return string The regular expression
 743   */
 744  function _get_wptexturize_shortcode_regex( $tagnames ) {
 745      $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
 746      $tagregexp = "(?:$tagregexp)(?=[\\s\\]\\/])"; // Excerpt of get_shortcode_regex().
 747      // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 748      $regex =
 749          '\['                // Find start of shortcode.
 750          . '[\/\[]?'         // Shortcodes may begin with [/ or [[.
 751          . $tagregexp        // Only match registered shortcodes, because performance.
 752          . '(?:'
 753          .     '[^\[\]<>]+'  // Shortcodes do not contain other shortcodes. Quantifier critical.
 754          . '|'
 755          .     '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
 756          . ')*+'             // Possessive critical.
 757          . '\]'              // Find end of shortcode.
 758          . '\]?';            // Shortcodes may end with ]].
 759      // phpcs:enable
 760  
 761      return $regex;
 762  }
 763  
 764  /**
 765   * Replace characters or phrases within HTML elements only.
 766   *
 767   * @since 4.2.3
 768   *
 769   * @param string $haystack The text which has to be formatted.
 770   * @param array $replace_pairs In the form array('from' => 'to', ...).
 771   * @return string The formatted text.
 772   */
 773  function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
 774      // Find all elements.
 775      $textarr = wp_html_split( $haystack );
 776      $changed = false;
 777  
 778      // Optimize when searching for one item.
 779      if ( 1 === count( $replace_pairs ) ) {
 780          // Extract $needle and $replace.
 781          foreach ( $replace_pairs as $needle => $replace ) {
 782          }
 783  
 784          // Loop through delimiters (elements) only.
 785          for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
 786              if ( false !== strpos( $textarr[ $i ], $needle ) ) {
 787                  $textarr[ $i ] = str_replace( $needle, $replace, $textarr[ $i ] );
 788                  $changed       = true;
 789              }
 790          }
 791      } else {
 792          // Extract all $needles.
 793          $needles = array_keys( $replace_pairs );
 794  
 795          // Loop through delimiters (elements) only.
 796          for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
 797              foreach ( $needles as $needle ) {
 798                  if ( false !== strpos( $textarr[ $i ], $needle ) ) {
 799                      $textarr[ $i ] = strtr( $textarr[ $i ], $replace_pairs );
 800                      $changed       = true;
 801                      // After one strtr() break out of the foreach loop and look at next element.
 802                      break;
 803                  }
 804              }
 805          }
 806      }
 807  
 808      if ( $changed ) {
 809          $haystack = implode( $textarr );
 810      }
 811  
 812      return $haystack;
 813  }
 814  
 815  /**
 816   * Newline preservation help function for wpautop
 817   *
 818   * @since 3.1.0
 819   * @access private
 820   *
 821   * @param array $matches preg_replace_callback matches array
 822   * @return string
 823   */
 824  function _autop_newline_preservation_helper( $matches ) {
 825      return str_replace( "\n", '<WPPreserveNewline />', $matches[0] );
 826  }
 827  
 828  /**
 829   * Don't auto-p wrap shortcodes that stand alone
 830   *
 831   * Ensures that shortcodes are not wrapped in `<p>...</p>`.
 832   *
 833   * @since 2.9.0
 834   *
 835   * @global array $shortcode_tags
 836   *
 837   * @param string $pee The content.
 838   * @return string The filtered content.
 839   */
 840  function shortcode_unautop( $pee ) {
 841      global $shortcode_tags;
 842  
 843      if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {
 844          return $pee;
 845      }
 846  
 847      $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
 848      $spaces    = wp_spaces_regexp();
 849  
 850      // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound,WordPress.WhiteSpace.PrecisionAlignment.Found -- don't remove regex indentation
 851      $pattern =
 852          '/'
 853          . '<p>'                              // Opening paragraph.
 854          . '(?:' . $spaces . ')*+'            // Optional leading whitespace.
 855          . '('                                // 1: The shortcode.
 856          .     '\\['                          // Opening bracket.
 857          .     "($tagregexp)"                 // 2: Shortcode name.
 858          .     '(?![\\w-])'                   // Not followed by word character or hyphen.
 859                                               // Unroll the loop: Inside the opening shortcode tag.
 860          .     '[^\\]\\/]*'                   // Not a closing bracket or forward slash.
 861          .     '(?:'
 862          .         '\\/(?!\\])'               // A forward slash not followed by a closing bracket.
 863          .         '[^\\]\\/]*'               // Not a closing bracket or forward slash.
 864          .     ')*?'
 865          .     '(?:'
 866          .         '\\/\\]'                   // Self closing tag and closing bracket.
 867          .     '|'
 868          .         '\\]'                      // Closing bracket.
 869          .         '(?:'                      // Unroll the loop: Optionally, anything between the opening and closing shortcode tags.
 870          .             '[^\\[]*+'             // Not an opening bracket.
 871          .             '(?:'
 872          .                 '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag.
 873          .                 '[^\\[]*+'         // Not an opening bracket.
 874          .             ')*+'
 875          .             '\\[\\/\\2\\]'         // Closing shortcode tag.
 876          .         ')?'
 877          .     ')'
 878          . ')'
 879          . '(?:' . $spaces . ')*+'            // Optional trailing whitespace.
 880          . '<\\/p>'                           // Closing paragraph.
 881          . '/';
 882      // phpcs:enable
 883  
 884      return preg_replace( $pattern, '$1', $pee );
 885  }
 886  
 887  /**
 888   * Checks to see if a string is utf8 encoded.
 889   *
 890   * NOTE: This function checks for 5-Byte sequences, UTF8
 891   *       has Bytes Sequences with a maximum length of 4.
 892   *
 893   * @author bmorel at ssi dot fr (modified)
 894   * @since 1.2.1
 895   *
 896   * @param string $str The string to be checked
 897   * @return bool True if $str fits a UTF-8 model, false otherwise.
 898   */
 899  function seems_utf8( $str ) {
 900      mbstring_binary_safe_encoding();
 901      $length = strlen( $str );
 902      reset_mbstring_encoding();
 903      for ( $i = 0; $i < $length; $i++ ) {
 904          $c = ord( $str[ $i ] );
 905          if ( $c < 0x80 ) {
 906              $n = 0; // 0bbbbbbb
 907          } elseif ( ( $c & 0xE0 ) == 0xC0 ) {
 908              $n = 1; // 110bbbbb
 909          } elseif ( ( $c & 0xF0 ) == 0xE0 ) {
 910              $n = 2; // 1110bbbb
 911          } elseif ( ( $c & 0xF8 ) == 0xF0 ) {
 912              $n = 3; // 11110bbb
 913          } elseif ( ( $c & 0xFC ) == 0xF8 ) {
 914              $n = 4; // 111110bb
 915          } elseif ( ( $c & 0xFE ) == 0xFC ) {
 916              $n = 5; // 1111110b
 917          } else {
 918              return false; // Does not match any model.
 919          }
 920          for ( $j = 0; $j < $n; $j++ ) { // n bytes matching 10bbbbbb follow ?
 921              if ( ( ++$i == $length ) || ( ( ord( $str[ $i ] ) & 0xC0 ) != 0x80 ) ) {
 922                  return false;
 923              }
 924          }
 925      }
 926      return true;
 927  }
 928  
 929  /**
 930   * Converts a number of special characters into their HTML entities.
 931   *
 932   * Specifically deals with: &, <, >, ", and '.
 933   *
 934   * $quote_style can be set to ENT_COMPAT to encode " to
 935   * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
 936   *
 937   * @since 1.2.2
 938   * @access private
 939   *
 940   * @staticvar string $_charset
 941   *
 942   * @param string       $string        The text which is to be encoded.
 943   * @param int|string   $quote_style   Optional. Converts double quotes if set to ENT_COMPAT,
 944   *                                    both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES.
 945   *                                    Also compatible with old values; converting single quotes if set to 'single',
 946   *                                    double if set to 'double' or both if otherwise set.
 947   *                                    Default is ENT_NOQUOTES.
 948   * @param false|string $charset       Optional. The character encoding of the string. Default is false.
 949   * @param bool         $double_encode Optional. Whether to encode existing html entities. Default is false.
 950   * @return string The encoded text with HTML entities.
 951   */
 952  function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
 953      $string = (string) $string;
 954  
 955      if ( 0 === strlen( $string ) ) {
 956          return '';
 957      }
 958  
 959      // Don't bother if there are no specialchars - saves some processing.
 960      if ( ! preg_match( '/[&<>"\']/', $string ) ) {
 961          return $string;
 962      }
 963  
 964      // Account for the previous behaviour of the function when the $quote_style is not an accepted value.
 965      if ( empty( $quote_style ) ) {
 966          $quote_style = ENT_NOQUOTES;
 967      } elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
 968          $quote_style = ENT_QUOTES;
 969      }
 970  
 971      // Store the site charset as a static to avoid multiple calls to wp_load_alloptions().
 972      if ( ! $charset ) {
 973          static $_charset = null;
 974          if ( ! isset( $_charset ) ) {
 975              $alloptions = wp_load_alloptions();
 976              $_charset   = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
 977          }
 978          $charset = $_charset;
 979      }
 980  
 981      if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ), true ) ) {
 982          $charset = 'UTF-8';
 983      }
 984  
 985      $_quote_style = $quote_style;
 986  
 987      if ( 'double' === $quote_style ) {
 988          $quote_style  = ENT_COMPAT;
 989          $_quote_style = ENT_COMPAT;
 990      } elseif ( 'single' === $quote_style ) {
 991          $quote_style = ENT_NOQUOTES;
 992      }
 993  
 994      if ( ! $double_encode ) {
 995          // Guarantee every &entity; is valid, convert &garbage; into &amp;garbage;
 996          // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
 997          $string = wp_kses_normalize_entities( $string );
 998      }
 999  
1000      $string = htmlspecialchars( $string, $quote_style, $charset, $double_encode );
1001  
1002      // Back-compat.
1003      if ( 'single' === $_quote_style ) {
1004          $string = str_replace( "'", '&#039;', $string );
1005      }
1006  
1007      return $string;
1008  }
1009  
1010  /**
1011   * Converts a number of HTML entities into their special characters.
1012   *
1013   * Specifically deals with: &, <, >, ", and '.
1014   *
1015   * $quote_style can be set to ENT_COMPAT to decode " entities,
1016   * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
1017   *
1018   * @since 2.8.0
1019   *
1020   * @param string     $string The text which is to be decoded.
1021   * @param string|int $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
1022   *                                both single and double if set to ENT_QUOTES or
1023   *                                none if set to ENT_NOQUOTES.
1024   *                                Also compatible with old _wp_specialchars() values;
1025   *                                converting single quotes if set to 'single',
1026   *                                double if set to 'double' or both if otherwise set.
1027   *                                Default is ENT_NOQUOTES.
1028   * @return string The decoded text without HTML entities.
1029   */
1030  function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
1031      $string = (string) $string;
1032  
1033      if ( 0 === strlen( $string ) ) {
1034          return '';
1035      }
1036  
1037      // Don't bother if there are no entities - saves a lot of processing.
1038      if ( strpos( $string, '&' ) === false ) {
1039          return $string;
1040      }
1041  
1042      // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value.
1043      if ( empty( $quote_style ) ) {
1044          $quote_style = ENT_NOQUOTES;
1045      } elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
1046          $quote_style = ENT_QUOTES;
1047      }
1048  
1049      // More complete than get_html_translation_table( HTML_SPECIALCHARS ).
1050      $single      = array(
1051          '&#039;' => '\'',
1052          '&#x27;' => '\'',
1053      );
1054      $single_preg = array(
1055          '/&#0*39;/'   => '&#039;',
1056          '/&#x0*27;/i' => '&#x27;',
1057      );
1058      $double      = array(
1059          '&quot;' => '"',
1060          '&#034;' => '"',
1061          '&#x22;' => '"',
1062      );
1063      $double_preg = array(
1064          '/&#0*34;/'   => '&#034;',
1065          '/&#x0*22;/i' => '&#x22;',
1066      );
1067      $others      = array(
1068          '&lt;'   => '<',
1069          '&#060;' => '<',
1070          '&gt;'   => '>',
1071          '&#062;' => '>',
1072          '&amp;'  => '&',
1073          '&#038;' => '&',
1074          '&#x26;' => '&',
1075      );
1076      $others_preg = array(
1077          '/&#0*60;/'   => '&#060;',
1078          '/&#0*62;/'   => '&#062;',
1079          '/&#0*38;/'   => '&#038;',
1080          '/&#x0*26;/i' => '&#x26;',
1081      );
1082  
1083      if ( ENT_QUOTES === $quote_style ) {
1084          $translation      = array_merge( $single, $double, $others );
1085          $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
1086      } elseif ( ENT_COMPAT === $quote_style || 'double' === $quote_style ) {
1087          $translation      = array_merge( $double, $others );
1088          $translation_preg = array_merge( $double_preg, $others_preg );
1089      } elseif ( 'single' === $quote_style ) {
1090          $translation      = array_merge( $single, $others );
1091          $translation_preg = array_merge( $single_preg, $others_preg );
1092      } elseif ( ENT_NOQUOTES === $quote_style ) {
1093          $translation      = $others;
1094          $translation_preg = $others_preg;
1095      }
1096  
1097      // Remove zero padding on numeric entities.
1098      $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
1099  
1100      // Replace characters according to translation table.
1101      return strtr( $string, $translation );
1102  }
1103  
1104  /**
1105   * Checks for invalid UTF8 in a string.
1106   *
1107   * @since 2.8.0
1108   *
1109   * @staticvar bool $is_utf8
1110   * @staticvar bool $utf8_pcre
1111   *
1112   * @param string  $string The text which is to be checked.
1113   * @param bool    $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
1114   * @return string The checked text.
1115   */
1116  function wp_check_invalid_utf8( $string, $strip = false ) {
1117      $string = (string) $string;
1118  
1119      if ( 0 === strlen( $string ) ) {
1120          return '';
1121      }
1122  
1123      // Store the site charset as a static to avoid multiple calls to get_option().
1124      static $is_utf8 = null;
1125      if ( ! isset( $is_utf8 ) ) {
1126          $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ), true );
1127      }
1128      if ( ! $is_utf8 ) {
1129          return $string;
1130      }
1131  
1132      // Check for support for utf8 in the installed PCRE library once and store the result in a static.
1133      static $utf8_pcre = null;
1134      if ( ! isset( $utf8_pcre ) ) {
1135          // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1136          $utf8_pcre = @preg_match( '/^./u', 'a' );
1137      }
1138      // We can't demand utf8 in the PCRE installation, so just return the string in those cases.
1139      if ( ! $utf8_pcre ) {
1140          return $string;
1141      }
1142  
1143      // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- preg_match fails when it encounters invalid UTF8 in $string.
1144      if ( 1 === @preg_match( '/^./us', $string ) ) {
1145          return $string;
1146      }
1147  
1148      // Attempt to strip the bad chars if requested (not recommended).
1149      if ( $strip && function_exists( 'iconv' ) ) {
1150          return iconv( 'utf-8', 'utf-8', $string );
1151      }
1152  
1153      return '';
1154  }
1155  
1156  /**
1157   * Encode the Unicode values to be used in the URI.
1158   *
1159   * @since 1.5.0
1160   *
1161   * @param string $utf8_string
1162   * @param int    $length Max  length of the string
1163   * @return string String with Unicode encoded for URI.
1164   */
1165  function utf8_uri_encode( $utf8_string, $length = 0 ) {
1166      $unicode        = '';
1167      $values         = array();
1168      $num_octets     = 1;
1169      $unicode_length = 0;
1170  
1171      mbstring_binary_safe_encoding();
1172      $string_length = strlen( $utf8_string );
1173      reset_mbstring_encoding();
1174  
1175      for ( $i = 0; $i < $string_length; $i++ ) {
1176  
1177          $value = ord( $utf8_string[ $i ] );
1178  
1179          if ( $value < 128 ) {
1180              if ( $length && ( $unicode_length >= $length ) ) {
1181                  break;
1182              }
1183              $unicode .= chr( $value );
1184              $unicode_length++;
1185          } else {
1186              if ( count( $values ) == 0 ) {
1187                  if ( $value < 224 ) {
1188                      $num_octets = 2;
1189                  } elseif ( $value < 240 ) {
1190                      $num_octets = 3;
1191                  } else {
1192                      $num_octets = 4;
1193                  }
1194              }
1195  
1196              $values[] = $value;
1197  
1198              if ( $length && ( $unicode_length + ( $num_octets * 3 ) ) > $length ) {
1199                  break;
1200              }
1201              if ( count( $values ) == $num_octets ) {
1202                  for ( $j = 0; $j < $num_octets; $j++ ) {
1203                      $unicode .= '%' . dechex( $values[ $j ] );
1204                  }
1205  
1206                  $unicode_length += $num_octets * 3;
1207  
1208                  $values     = array();
1209                  $num_octets = 1;
1210              }
1211          }
1212      }
1213  
1214      return $unicode;
1215  }
1216  
1217  /**
1218   * Converts all accent characters to ASCII characters.
1219   *
1220   * If there are no accent characters, then the string given is just returned.
1221   *
1222   * **Accent characters converted:**
1223   *
1224   * Currency signs:
1225   *
1226   * |   Code   | Glyph | Replacement |     Description     |
1227   * | -------- | ----- | ----------- | ------------------- |
1228   * | U+00A3   | £     | (empty)     | British Pound sign  |
1229   * | U+20AC   | €     | E           | Euro sign           |
1230   *
1231   * Decompositions for Latin-1 Supplement:
1232   *
1233   * |  Code   | Glyph | Replacement |               Description              |
1234   * | ------- | ----- | ----------- | -------------------------------------- |
1235   * | U+00AA  | ª     | a           | Feminine ordinal indicator             |
1236   * | U+00BA  | º     | o           | Masculine ordinal indicator            |
1237   * | U+00C0  | À     | A           | Latin capital letter A with grave      |
1238   * | U+00C1  | Á     | A           | Latin capital letter A with acute      |
1239   * | U+00C2  | Â     | A           | Latin capital letter A with circumflex |
1240   * | U+00C3  | Ã     | A           | Latin capital letter A with tilde      |
1241   * | U+00C4  | Ä     | A           | Latin capital letter A with diaeresis  |
1242   * | U+00C5  | Å     | A           | Latin capital letter A with ring above |
1243   * | U+00C6  | Æ     | AE          | Latin capital letter AE                |
1244   * | U+00C7  | Ç     | C           | Latin capital letter C with cedilla    |
1245   * | U+00C8  | È     | E           | Latin capital letter E with grave      |
1246   * | U+00C9  | É     | E           | Latin capital letter E with acute      |
1247   * | U+00CA  | Ê     | E           | Latin capital letter E with circumflex |
1248   * | U+00CB  | Ë     | E           | Latin capital letter E with diaeresis  |
1249   * | U+00CC  | Ì     | I           | Latin capital letter I with grave      |
1250   * | U+00CD  | Í     | I           | Latin capital letter I with acute      |
1251   * | U+00CE  | Î     | I           | Latin capital letter I with circumflex |
1252   * | U+00CF  | Ï     | I           | Latin capital letter I with diaeresis  |
1253   * | U+00D0  | Ð     | D           | Latin capital letter Eth               |
1254   * | U+00D1  | Ñ     | N           | Latin capital letter N with tilde      |
1255   * | U+00D2  | Ò     | O           | Latin capital letter O with grave      |
1256   * | U+00D3  | Ó     | O           | Latin capital letter O with acute      |
1257   * | U+00D4  | Ô     | O           | Latin capital letter O with circumflex |
1258   * | U+00D5  | Õ     | O           | Latin capital letter O with tilde      |
1259   * | U+00D6  | Ö     | O           | Latin capital letter O with diaeresis  |
1260   * | U+00D8  | Ø     | O           | Latin capital letter O with stroke     |
1261   * | U+00D9  | Ù     | U           | Latin capital letter U with grave      |
1262   * | U+00DA  | Ú     | U           | Latin capital letter U with acute      |
1263   * | U+00DB  | Û     | U           | Latin capital letter U with circumflex |
1264   * | U+00DC  | Ü     | U           | Latin capital letter U with diaeresis  |
1265   * | U+00DD  | Ý     | Y           | Latin capital letter Y with acute      |
1266   * | U+00DE  | Þ     | TH          | Latin capital letter Thorn             |
1267   * | U+00DF  | ß     | s           | Latin small letter sharp s             |
1268   * | U+00E0  | à     | a           | Latin small letter a with grave        |
1269   * | U+00E1  | á     | a           | Latin small letter a with acute        |
1270   * | U+00E2  | â     | a           | Latin small letter a with circumflex   |
1271   * | U+00E3  | ã     | a           | Latin small letter a with tilde        |
1272   * | U+00E4  | ä     | a           | Latin small letter a with diaeresis    |
1273   * | U+00E5  | å     | a           | Latin small letter a with ring above   |
1274   * | U+00E6  | æ     | ae          | Latin small letter ae                  |
1275   * | U+00E7  | ç     | c           | Latin small letter c with cedilla      |
1276   * | U+00E8  | è     | e           | Latin small letter e with grave        |
1277   * | U+00E9  | é     | e           | Latin small letter e with acute        |
1278   * | U+00EA  | ê     | e           | Latin small letter e with circumflex   |
1279   * | U+00EB  | ë     | e           | Latin small letter e with diaeresis    |
1280   * | U+00EC  | ì     | i           | Latin small letter i with grave        |
1281   * | U+00ED  | í     | i           | Latin small letter i with acute        |
1282   * | U+00EE  | î     | i           | Latin small letter i with circumflex   |
1283   * | U+00EF  | ï     | i           | Latin small letter i with diaeresis    |
1284   * | U+00F0  | ð     | d           | Latin small letter Eth                 |
1285   * | U+00F1  | ñ     | n           | Latin small letter n with tilde        |
1286   * | U+00F2  | ò     | o           | Latin small letter o with grave        |
1287   * | U+00F3  | ó     | o           | Latin small letter o with acute        |
1288   * | U+00F4  | ô     | o           | Latin small letter o with circumflex   |
1289   * | U+00F5  | õ     | o           | Latin small letter o with tilde        |
1290   * | U+00F6  | ö     | o           | Latin small letter o with diaeresis    |
1291   * | U+00F8  | ø     | o           | Latin small letter o with stroke       |
1292   * | U+00F9  | ù     | u           | Latin small letter u with grave        |
1293   * | U+00FA  | ú     | u           | Latin small letter u with acute        |
1294   * | U+00FB  | û     | u           | Latin small letter u with circumflex   |
1295   * | U+00FC  | ü     | u           | Latin small letter u with diaeresis    |
1296   * | U+00FD  | ý     | y           | Latin small letter y with acute        |
1297   * | U+00FE  | þ     | th          | Latin small letter Thorn               |
1298   * | U+00FF  | ÿ     | y           | Latin small letter y with diaeresis    |
1299   *
1300   * Decompositions for Latin Extended-A:
1301   *
1302   * |  Code   | Glyph | Replacement |                    Description                    |
1303   * | ------- | ----- | ----------- | ------------------------------------------------- |
1304   * | U+0100  | Ā     | A           | Latin capital letter A with macron                |
1305   * | U+0101  | ā     | a           | Latin small letter a with macron                  |
1306   * | U+0102  | Ă     | A           | Latin capital letter A with breve                 |
1307   * | U+0103  | ă     | a           | Latin small letter a with breve                   |
1308   * | U+0104  | Ą     | A           | Latin capital letter A with ogonek                |
1309   * | U+0105  | ą     | a           | Latin small letter a with ogonek                  |
1310   * | U+01006 | Ć     | C           | Latin capital letter C with acute                 |
1311   * | U+0107  | ć     | c           | Latin small letter c with acute                   |
1312   * | U+0108  | Ĉ     | C           | Latin capital letter C with circumflex            |
1313   * | U+0109  | ĉ     | c           | Latin small letter c with circumflex              |
1314   * | U+010A  | Ċ     | C           | Latin capital letter C with dot above             |
1315   * | U+010B  | ċ     | c           | Latin small letter c with dot above               |
1316   * | U+010C  | Č     | C           | Latin capital letter C with caron                 |
1317   * | U+010D  | č     | c           | Latin small letter c with caron                   |
1318   * | U+010E  | Ď     | D           | Latin capital letter D with caron                 |
1319   * | U+010F  | ď     | d           | Latin small letter d with caron                   |
1320   * | U+0110  | Đ     | D           | Latin capital letter D with stroke                |
1321   * | U+0111  | đ     | d           | Latin small letter d with stroke                  |
1322   * | U+0112  | Ē     | E           | Latin capital letter E with macron                |
1323   * | U+0113  | ē     | e           | Latin small letter e with macron                  |
1324   * | U+0114  | Ĕ     | E           | Latin capital letter E with breve                 |
1325   * | U+0115  | ĕ     | e           | Latin small letter e with breve                   |
1326   * | U+0116  | Ė     | E           | Latin capital letter E with dot above             |
1327   * | U+0117  | ė     | e           | Latin small letter e with dot above               |
1328   * | U+0118  | Ę     | E           | Latin capital letter E with ogonek                |
1329   * | U+0119  | ę     | e           | Latin small letter e with ogonek                  |
1330   * | U+011A  | Ě     | E           | Latin capital letter E with caron                 |
1331   * | U+011B  | ě     | e           | Latin small letter e with caron                   |
1332   * | U+011C  | Ĝ     | G           | Latin capital letter G with circumflex            |
1333   * | U+011D  | ĝ     | g           | Latin small letter g with circumflex              |
1334   * | U+011E  | Ğ     | G           | Latin capital letter G with breve                 |
1335   * | U+011F  | ğ     | g           | Latin small letter g with breve                   |
1336   * | U+0120  | Ġ     | G           | Latin capital letter G with dot above             |
1337   * | U+0121  | ġ     | g           | Latin small letter g with dot above               |
1338   * | U+0122  | Ģ     | G           | Latin capital letter G with cedilla               |
1339   * | U+0123  | ģ     | g           | Latin small letter g with cedilla                 |
1340   * | U+0124  | Ĥ     | H           | Latin capital letter H with circumflex            |
1341   * | U+0125  | ĥ     | h           | Latin small letter h with circumflex              |
1342   * | U+0126  | Ħ     | H           | Latin capital letter H with stroke                |
1343   * | U+0127  | ħ     | h           | Latin small letter h with stroke                  |
1344   * | U+0128  | Ĩ     | I           | Latin capital letter I with tilde                 |
1345   * | U+0129  | ĩ     | i           | Latin small letter i with tilde                   |
1346   * | U+012A  | Ī     | I           | Latin capital letter I with macron                |
1347   * | U+012B  | ī     | i           | Latin small letter i with macron                  |
1348   * | U+012C  | Ĭ     | I           | Latin capital letter I with breve                 |
1349   * | U+012D  | ĭ     | i           | Latin small letter i with breve                   |
1350   * | U+012E  | Į     | I           | Latin capital letter I with ogonek                |
1351   * | U+012F  | į     | i           | Latin small letter i with ogonek                  |
1352   * | U+0130  | İ     | I           | Latin capital letter I with dot above             |
1353   * | U+0131  | ı     | i           | Latin small letter dotless i                      |
1354   * | U+0132  | IJ     | IJ          | Latin capital ligature IJ                         |
1355   * | U+0133  | ij     | ij          | Latin small ligature ij                           |
1356   * | U+0134  | Ĵ     | J           | Latin capital letter J with circumflex            |
1357   * | U+0135  | ĵ     | j           | Latin small letter j with circumflex              |
1358   * | U+0136  | Ķ     | K           | Latin capital letter K with cedilla               |
1359   * | U+0137  | ķ     | k           | Latin small letter k with cedilla                 |
1360   * | U+0138  | ĸ     | k           | Latin small letter Kra                            |
1361   * | U+0139  | Ĺ     | L           | Latin capital letter L with acute                 |
1362   * | U+013A  | ĺ     | l           | Latin small letter l with acute                   |
1363   * | U+013B  | Ļ     | L           | Latin capital letter L with cedilla               |
1364   * | U+013C  | ļ     | l           | Latin small letter l with cedilla                 |
1365   * | U+013D  | Ľ     | L           | Latin capital letter L with caron                 |
1366   * | U+013E  | ľ     | l           | Latin small letter l with caron                   |
1367   * | U+013F  | Ŀ     | L           | Latin capital letter L with middle dot            |
1368   * | U+0140  | ŀ     | l           | Latin small letter l with middle dot              |
1369   * | U+0141  | Ł     | L           | Latin capital letter L with stroke                |
1370   * | U+0142  | ł     | l           | Latin small letter l with stroke                  |
1371   * | U+0143  | Ń     | N           | Latin capital letter N with acute                 |
1372   * | U+0144  | ń     | n           | Latin small letter N with acute                   |
1373   * | U+0145  | Ņ     | N           | Latin capital letter N with cedilla               |
1374   * | U+0146  | ņ     | n           | Latin small letter n with cedilla                 |
1375   * | U+0147  | Ň     | N           | Latin capital letter N with caron                 |
1376   * | U+0148  | ň     | n           | Latin small letter n with caron                   |
1377   * | U+0149  | ʼn     | n           | Latin small letter n preceded by apostrophe       |
1378   * | U+014A  | Ŋ     | N           | Latin capital letter Eng                          |
1379   * | U+014B  | ŋ     | n           | Latin small letter Eng                            |
1380   * | U+014C  | Ō     | O           | Latin capital letter O with macron                |
1381   * | U+014D  | ō     | o           | Latin small letter o with macron                  |
1382   * | U+014E  | Ŏ     | O           | Latin capital letter O with breve                 |
1383   * | U+014F  | ŏ     | o           | Latin small letter o with breve                   |
1384   * | U+0150  | Ő     | O           | Latin capital letter O with double acute          |
1385   * | U+0151  | ő     | o           | Latin small letter o with double acute            |
1386   * | U+0152  | Π    | OE          | Latin capital ligature OE                         |
1387   * | U+0153  | œ     | oe          | Latin small ligature oe                           |
1388   * | U+0154  | Ŕ     | R           | Latin capital letter R with acute                 |
1389   * | U+0155  | ŕ     | r           | Latin small letter r with acute                   |
1390   * | U+0156  | Ŗ     | R           | Latin capital letter R with cedilla               |
1391   * | U+0157  | ŗ     | r           | Latin small letter r with cedilla                 |
1392   * | U+0158  | Ř     | R           | Latin capital letter R with caron                 |
1393   * | U+0159  | ř     | r           | Latin small letter r with caron                   |
1394   * | U+015A  | Ś     | S           | Latin capital letter S with acute                 |
1395   * | U+015B  | ś     | s           | Latin small letter s with acute                   |
1396   * | U+015C  | Ŝ     | S           | Latin capital letter S with circumflex            |
1397   * | U+015D  | ŝ     | s           | Latin small letter s with circumflex              |
1398   * | U+015E  | Ş     | S           | Latin capital letter S with cedilla               |
1399   * | U+015F  | ş     | s           | Latin small letter s with cedilla                 |
1400   * | U+0160  | Š     | S           | Latin capital letter S with caron                 |
1401   * | U+0161  | š     | s           | Latin small letter s with caron                   |
1402   * | U+0162  | Ţ     | T           | Latin capital letter T with cedilla               |
1403   * | U+0163  | ţ     | t           | Latin small letter t with cedilla                 |
1404   * | U+0164  | Ť     | T           | Latin capital letter T with caron                 |
1405   * | U+0165  | ť     | t           | Latin small letter t with caron                   |
1406   * | U+0166  | Ŧ     | T           | Latin capital letter T with stroke                |
1407   * | U+0167  | ŧ     | t           | Latin small letter t with stroke                  |
1408   * | U+0168  | Ũ     | U           | Latin capital letter U with tilde                 |
1409   * | U+0169  | ũ     | u           | Latin small letter u with tilde                   |
1410   * | U+016A  | Ū     | U           | Latin capital letter U with macron                |
1411   * | U+016B  | ū     | u           | Latin small letter u with macron                  |
1412   * | U+016C  | Ŭ     | U           | Latin capital letter U with breve                 |
1413   * | U+016D  | ŭ     | u           | Latin small letter u with breve                   |
1414   * | U+016E  | Ů     | U           | Latin capital letter U with ring above            |
1415   * | U+016F  | ů     | u           | Latin small letter u with ring above              |
1416   * | U+0170  | Ű     | U           | Latin capital letter U with double acute          |
1417   * | U+0171  | ű     | u           | Latin small letter u with double acute            |
1418   * | U+0172  | Ų     | U           | Latin capital letter U with ogonek                |
1419   * | U+0173  | ų     | u           | Latin small letter u with ogonek                  |
1420   * | U+0174  | Ŵ     | W           | Latin capital letter W with circumflex            |
1421   * | U+0175  | ŵ     | w           | Latin small letter w with circumflex              |
1422   * | U+0176  | Ŷ     | Y           | Latin capital letter Y with circumflex            |
1423   * | U+0177  | ŷ     | y           | Latin small letter y with circumflex              |
1424   * | U+0178  | Ÿ     | Y           | Latin capital letter Y with diaeresis             |
1425   * | U+0179  | Ź     | Z           | Latin capital letter Z with acute                 |
1426   * | U+017A  | ź     | z           | Latin small letter z with acute                   |
1427   * | U+017B  | Ż     | Z           | Latin capital letter Z with dot above             |
1428   * | U+017C  | ż     | z           | Latin small letter z with dot above               |
1429   * | U+017D  | Ž     | Z           | Latin capital letter Z with caron                 |
1430   * | U+017E  | ž     | z           | Latin small letter z with caron                   |
1431   * | U+017F  | ſ     | s           | Latin small letter long s                         |
1432   * | U+01A0  | Ơ     | O           | Latin capital letter O with horn                  |
1433   * | U+01A1  | ơ     | o           | Latin small letter o with horn                    |
1434   * | U+01AF  | Ư     | U           | Latin capital letter U with horn                  |
1435   * | U+01B0  | ư     | u           | Latin small letter u with horn                    |
1436   * | U+01CD  | Ǎ     | A           | Latin capital letter A with caron                 |
1437   * | U+01CE  | ǎ     | a           | Latin small letter a with caron                   |
1438   * | U+01CF  | Ǐ     | I           | Latin capital letter I with caron                 |
1439   * | U+01D0  | ǐ     | i           | Latin small letter i with caron                   |
1440   * | U+01D1  | Ǒ     | O           | Latin capital letter O with caron                 |
1441   * | U+01D2  | ǒ     | o           | Latin small letter o with caron                   |
1442   * | U+01D3  | Ǔ     | U           | Latin capital letter U with caron                 |
1443   * | U+01D4  | ǔ     | u           | Latin small letter u with caron                   |
1444   * | U+01D5  | Ǖ     | U           | Latin capital letter U with diaeresis and macron  |
1445   * | U+01D6  | ǖ     | u           | Latin small letter u with diaeresis and macron    |
1446   * | U+01D7  | Ǘ     | U           | Latin capital letter U with diaeresis and acute   |
1447   * | U+01D8  | ǘ     | u           | Latin small letter u with diaeresis and acute     |
1448   * | U+01D9  | Ǚ     | U           | Latin capital letter U with diaeresis and caron   |
1449   * | U+01DA  | ǚ     | u           | Latin small letter u with diaeresis and caron     |
1450   * | U+01DB  | Ǜ     | U           | Latin capital letter U with diaeresis and grave   |
1451   * | U+01DC  | ǜ     | u           | Latin small letter u with diaeresis and grave     |
1452   *
1453   * Decompositions for Latin Extended-B:
1454   *
1455   * |   Code   | Glyph | Replacement |                Description                |
1456   * | -------- | ----- | ----------- | ----------------------------------------- |
1457   * | U+0218   | Ș     | S           | Latin capital letter S with comma below   |
1458   * | U+0219   | ș     | s           | Latin small letter s with comma below     |
1459   * | U+021A   | Ț     | T           | Latin capital letter T with comma below   |
1460   * | U+021B   | ț     | t           | Latin small letter t with comma below     |
1461   *
1462   * Vowels with diacritic (Chinese, Hanyu Pinyin):
1463   *
1464   * |   Code   | Glyph | Replacement |                      Description                      |
1465   * | -------- | ----- | ----------- | ----------------------------------------------------- |
1466   * | U+0251   | ɑ     | a           | Latin small letter alpha                              |
1467   * | U+1EA0   | Ạ     | A           | Latin capital letter A with dot below                 |
1468   * | U+1EA1   | ạ     | a           | Latin small letter a with dot below                   |
1469   * | U+1EA2   | Ả     | A           | Latin capital letter A with hook above                |
1470   * | U+1EA3   | ả     | a           | Latin small letter a with hook above                  |
1471   * | U+1EA4   | Ấ     | A           | Latin capital letter A with circumflex and acute      |
1472   * | U+1EA5   | ấ     | a           | Latin small letter a with circumflex and acute        |
1473   * | U+1EA6   | Ầ     | A           | Latin capital letter A with circumflex and grave      |
1474   * | U+1EA7   | ầ     | a           | Latin small letter a with circumflex and grave        |
1475   * | U+1EA8   | Ẩ     | A           | Latin capital letter A with circumflex and hook above |
1476   * | U+1EA9   | ẩ     | a           | Latin small letter a with circumflex and hook above   |
1477   * | U+1EAA   | Ẫ     | A           | Latin capital letter A with circumflex and tilde      |
1478   * | U+1EAB   | ẫ     | a           | Latin small letter a with circumflex and tilde        |
1479   * | U+1EA6   | Ậ     | A           | Latin capital letter A with circumflex and dot below  |
1480   * | U+1EAD   | ậ     | a           | Latin small letter a with circumflex and dot below    |
1481   * | U+1EAE   | Ắ     | A           | Latin capital letter A with breve and acute           |
1482   * | U+1EAF   | ắ     | a           | Latin small letter a with breve and acute             |
1483   * | U+1EB0   | Ằ     | A           | Latin capital letter A with breve and grave           |
1484   * | U+1EB1   | ằ     | a           | Latin small letter a with breve and grave             |
1485   * | U+1EB2   | Ẳ     | A           | Latin capital letter A with breve and hook above      |
1486   * | U+1EB3   | ẳ     | a           | Latin small letter a with breve and hook above        |
1487   * | U+1EB4   | Ẵ     | A           | Latin capital letter A with breve and tilde           |
1488   * | U+1EB5   | ẵ     | a           | Latin small letter a with breve and tilde             |
1489   * | U+1EB6   | Ặ     | A           | Latin capital letter A with breve and dot below       |
1490   * | U+1EB7   | ặ     | a           | Latin small letter a with breve and dot below         |
1491   * | U+1EB8   | Ẹ     | E           | Latin capital letter E with dot below                 |
1492   * | U+1EB9   | ẹ     | e           | Latin small letter e with dot below                   |
1493   * | U+1EBA   | Ẻ     | E           | Latin capital letter E with hook above                |
1494   * | U+1EBB   | ẻ     | e           | Latin small letter e with hook above                  |
1495   * | U+1EBC   | Ẽ     | E           | Latin capital letter E with tilde                     |
1496   * | U+1EBD   | ẽ     | e           | Latin small letter e with tilde                       |
1497   * | U+1EBE   | Ế     | E           | Latin capital letter E with circumflex and acute      |
1498   * | U+1EBF   | ế     | e           | Latin small letter e with circumflex and acute        |
1499   * | U+1EC0   | Ề     | E           | Latin capital letter E with circumflex and grave      |
1500   * | U+1EC1   | ề     | e           | Latin small letter e with circumflex and grave        |
1501   * | U+1EC2   | Ể     | E           | Latin capital letter E with circumflex and hook above |
1502   * | U+1EC3   | ể     | e           | Latin small letter e with circumflex and hook above   |
1503   * | U+1EC4   | Ễ     | E           | Latin capital letter E with circumflex and tilde      |
1504   * | U+1EC5   | ễ     | e           | Latin small letter e with circumflex and tilde        |
1505   * | U+1EC6   | Ệ     | E           | Latin capital letter E with circumflex and dot below  |
1506   * | U+1EC7   | ệ     | e           | Latin small letter e with circumflex and dot below    |
1507   * | U+1EC8   | Ỉ     | I           | Latin capital letter I with hook above                |
1508   * | U+1EC9   | ỉ     | i           | Latin small letter i with hook above                  |
1509   * | U+1ECA   | Ị     | I           | Latin capital letter I with dot below                 |
1510   * | U+1ECB   | ị     | i           | Latin small letter i with dot below                   |
1511   * | U+1ECC   | Ọ     | O           | Latin capital letter O with dot below                 |
1512   * | U+1ECD   | ọ     | o           | Latin small letter o with dot below                   |
1513   * | U+1ECE   | Ỏ     | O           | Latin capital letter O with hook above                |
1514   * | U+1ECF   | ỏ     | o           | Latin small letter o with hook above                  |
1515   * | U+1ED0   | Ố     | O           | Latin capital letter O with circumflex and acute      |
1516   * | U+1ED1   | ố     | o           | Latin small letter o with circumflex and acute        |
1517   * | U+1ED2   | Ồ     | O           | Latin capital letter O with circumflex and grave      |
1518   * | U+1ED3   | ồ     | o           | Latin small letter o with circumflex and grave        |
1519   * | U+1ED4   | Ổ     | O           | Latin capital letter O with circumflex and hook above |
1520   * | U+1ED5   | ổ     | o           | Latin small letter o with circumflex and hook above   |
1521   * | U+1ED6   | Ỗ     | O           | Latin capital letter O with circumflex and tilde      |
1522   * | U+1ED7   | ỗ     | o           | Latin small letter o with circumflex and tilde        |
1523   * | U+1ED8   | Ộ     | O           | Latin capital letter O with circumflex and dot below  |
1524   * | U+1ED9   | ộ     | o           | Latin small letter o with circumflex and dot below    |
1525   * | U+1EDA   | Ớ     | O           | Latin capital letter O with horn and acute            |
1526   * | U+1EDB   | ớ     | o           | Latin small letter o with horn and acute              |
1527   * | U+1EDC   | Ờ     | O           | Latin capital letter O with horn and grave            |
1528   * | U+1EDD   | ờ     | o           | Latin small letter o with horn and grave              |
1529   * | U+1EDE   | Ở     | O           | Latin capital letter O with horn and hook above       |
1530   * | U+1EDF   | ở     | o           | Latin small letter o with horn and hook above         |
1531   * | U+1EE0   | Ỡ     | O           | Latin capital letter O with horn and tilde            |
1532   * | U+1EE1   | ỡ     | o           | Latin small letter o with horn and tilde              |
1533   * | U+1EE2   | Ợ     | O           | Latin capital letter O with horn and dot below        |
1534   * | U+1EE3   | ợ     | o           | Latin small letter o with horn and dot below          |
1535   * | U+1EE4   | Ụ     | U           | Latin capital letter U with dot below                 |
1536   * | U+1EE5   | ụ     | u           | Latin small letter u with dot below                   |
1537   * | U+1EE6   | Ủ     | U           | Latin capital letter U with hook above                |
1538   * | U+1EE7   | ủ     | u           | Latin small letter u with hook above                  |
1539   * | U+1EE8   | Ứ     | U           | Latin capital letter U with horn and acute            |
1540   * | U+1EE9   | ứ     | u           | Latin small letter u with horn and acute              |
1541   * | U+1EEA   | Ừ     | U           | Latin capital letter U with horn and grave            |
1542   * | U+1EEB   | ừ     | u           | Latin small letter u with horn and grave              |
1543   * | U+1EEC   | Ử     | U           | Latin capital letter U with horn and hook above       |
1544   * | U+1EED   | ử     | u           | Latin small letter u with horn and hook above         |
1545   * | U+1EEE   | Ữ     | U           | Latin capital letter U with horn and tilde            |
1546   * | U+1EEF   | ữ     | u           | Latin small letter u with horn and tilde              |
1547   * | U+1EF0   | Ự     | U           | Latin capital letter U with horn and dot below        |
1548   * | U+1EF1   | ự     | u           | Latin small letter u with horn and dot below          |
1549   * | U+1EF2   | Ỳ     | Y           | Latin capital letter Y with grave                     |
1550   * | U+1EF3   | ỳ     | y           | Latin small letter y with grave                       |
1551   * | U+1EF4   | Ỵ     | Y           | Latin capital letter Y with dot below                 |
1552   * | U+1EF5   | ỵ     | y           | Latin small letter y with dot below                   |
1553   * | U+1EF6   | Ỷ     | Y           | Latin capital letter Y with hook above                |
1554   * | U+1EF7   | ỷ     | y           | Latin small letter y with hook above                  |
1555   * | U+1EF8   | Ỹ     | Y           | Latin capital letter Y with tilde                     |
1556   * | U+1EF9   | ỹ     | y           | Latin small letter y with tilde                       |
1557   *
1558   * German (`de_DE`), German formal (`de_DE_formal`), German (Switzerland) formal (`de_CH`),
1559   * and German (Switzerland) informal (`de_CH_informal`) locales:
1560   *
1561   * |   Code   | Glyph | Replacement |               Description               |
1562   * | -------- | ----- | ----------- | --------------------------------------- |
1563   * | U+00C4   | Ä     | Ae          | Latin capital letter A with diaeresis   |
1564   * | U+00E4   | ä     | ae          | Latin small letter a with diaeresis     |
1565   * | U+00D6   | Ö     | Oe          | Latin capital letter O with diaeresis   |
1566   * | U+00F6   | ö     | oe          | Latin small letter o with diaeresis     |
1567   * | U+00DC   | Ü     | Ue          | Latin capital letter U with diaeresis   |
1568   * | U+00FC   | ü     | ue          | Latin small letter u with diaeresis     |
1569   * | U+00DF   | ß     | ss          | Latin small letter sharp s              |
1570   *
1571   * Danish (`da_DK`) locale:
1572   *
1573   * |   Code   | Glyph | Replacement |               Description               |
1574   * | -------- | ----- | ----------- | --------------------------------------- |
1575   * | U+00C6   | Æ     | Ae          | Latin capital letter AE                 |
1576   * | U+00E6   | æ     | ae          | Latin small letter ae                   |
1577   * | U+00D8   | Ø     | Oe          | Latin capital letter O with stroke      |
1578   * | U+00F8   | ø     | oe          | Latin small letter o with stroke        |
1579   * | U+00C5   | Å     | Aa          | Latin capital letter A with ring above  |
1580   * | U+00E5   | å     | aa          | Latin small letter a with ring above    |
1581   *
1582   * Catalan (`ca`) locale:
1583   *
1584   * |   Code   | Glyph | Replacement |               Description               |
1585   * | -------- | ----- | ----------- | --------------------------------------- |
1586   * | U+00B7   | l·l   | ll          | Flown dot (between two Ls)              |
1587   *
1588   * Serbian (`sr_RS`) and Bosnian (`bs_BA`) locales:
1589   *
1590   * |   Code   | Glyph | Replacement |               Description               |
1591   * | -------- | ----- | ----------- | --------------------------------------- |
1592   * | U+0110   | Đ     | DJ          | Latin capital letter D with stroke      |
1593   * | U+0111   | đ     | dj          | Latin small letter d with stroke        |
1594   *
1595   * @since 1.2.1
1596   * @since 4.6.0 Added locale support for `de_CH`, `de_CH_informal`, and `ca`.
1597   * @since 4.7.0 Added locale support for `sr_RS`.
1598   * @since 4.8.0 Added locale support for `bs_BA`.
1599   *
1600   * @param string $string Text that might have accent characters
1601   * @return string Filtered string with replaced "nice" characters.
1602   */
1603  function remove_accents( $string ) {
1604      if ( ! preg_match( '/[\x80-\xff]/', $string ) ) {
1605          return $string;
1606      }
1607  
1608      if ( seems_utf8( $string ) ) {
1609          $chars = array(
1610              // Decompositions for Latin-1 Supplement.
1611              'ª' => 'a',
1612              'º' => 'o',
1613              'À' => 'A',
1614              'Á' => 'A',
1615              'Â' => 'A',
1616              'Ã' => 'A',
1617              'Ä' => 'A',
1618              'Å' => 'A',
1619              'Æ' => 'AE',
1620              'Ç' => 'C',
1621              'È' => 'E',
1622              'É' => 'E',
1623              'Ê' => 'E',
1624              'Ë' => 'E',
1625              'Ì' => 'I',
1626              'Í' => 'I',
1627              'Î' => 'I',
1628              'Ï' => 'I',
1629              'Ð' => 'D',
1630              'Ñ' => 'N',
1631              'Ò' => 'O',
1632              'Ó' => 'O',
1633              'Ô' => 'O',
1634              'Õ' => 'O',
1635              'Ö' => 'O',
1636              'Ù' => 'U',
1637              'Ú' => 'U',
1638              'Û' => 'U',
1639              'Ü' => 'U',
1640              'Ý' => 'Y',
1641              'Þ' => 'TH',
1642              'ß' => 's',
1643              'à' => 'a',
1644              'á' => 'a',
1645              'â' => 'a',
1646              'ã' => 'a',
1647              'ä' => 'a',
1648              'å' => 'a',
1649              'æ' => 'ae',
1650              'ç' => 'c',
1651              'è' => 'e',
1652              'é' => 'e',
1653              'ê' => 'e',
1654              'ë' => 'e',
1655              'ì' => 'i',
1656              'í' => 'i',
1657              'î' => 'i',
1658              'ï' => 'i',
1659              'ð' => 'd',
1660              'ñ' => 'n',
1661              'ò' => 'o',
1662              'ó' => 'o',
1663              'ô' => 'o',
1664              'õ' => 'o',
1665              'ö' => 'o',
1666              'ø' => 'o',
1667              'ù' => 'u',
1668              'ú' => 'u',
1669              'û' => 'u',
1670              'ü' => 'u',
1671              'ý' => 'y',
1672              'þ' => 'th',
1673              'ÿ' => 'y',
1674              'Ø' => 'O',
1675              // Decompositions for Latin Extended-A.
1676              'Ā' => 'A',
1677              'ā' => 'a',
1678              'Ă' => 'A',
1679              'ă' => 'a',
1680              'Ą' => 'A',
1681              'ą' => 'a',
1682              'Ć' => 'C',
1683              'ć' => 'c',
1684              'Ĉ' => 'C',
1685              'ĉ' => 'c',
1686              'Ċ' => 'C',
1687              'ċ' => 'c',
1688              'Č' => 'C',
1689              'č' => 'c',
1690              'Ď' => 'D',
1691              'ď' => 'd',
1692              'Đ' => 'D',
1693              'đ' => 'd',
1694              'Ē' => 'E',
1695              'ē' => 'e',
1696              'Ĕ' => 'E',
1697              'ĕ' => 'e',
1698              'Ė' => 'E',
1699              'ė' => 'e',
1700              'Ę' => 'E',
1701              'ę' => 'e',
1702              'Ě' => 'E',
1703              'ě' => 'e',
1704              'Ĝ' => 'G',
1705              'ĝ' => 'g',
1706              'Ğ' => 'G',
1707              'ğ' => 'g',
1708              'Ġ' => 'G',
1709              'ġ' => 'g',
1710              'Ģ' => 'G',
1711              'ģ' => 'g',
1712              'Ĥ' => 'H',
1713              'ĥ' => 'h',
1714              'Ħ' => 'H',
1715              'ħ' => 'h',
1716              'Ĩ' => 'I',
1717              'ĩ' => 'i',
1718              'Ī' => 'I',
1719              'ī' => 'i',
1720              'Ĭ' => 'I',
1721              'ĭ' => 'i',
1722              'Į' => 'I',
1723              'į' => 'i',
1724              'İ' => 'I',
1725              'ı' => 'i',
1726              'IJ' => 'IJ',
1727              'ij' => 'ij',
1728              'Ĵ' => 'J',
1729              'ĵ' => 'j',
1730              'Ķ' => 'K',
1731              'ķ' => 'k',
1732              'ĸ' => 'k',
1733              'Ĺ' => 'L',
1734              'ĺ' => 'l',
1735              'Ļ' => 'L',
1736              'ļ' => 'l',
1737              'Ľ' => 'L',
1738              'ľ' => 'l',
1739              'Ŀ' => 'L',
1740              'ŀ' => 'l',
1741              'Ł' => 'L',
1742              'ł' => 'l',
1743              'Ń' => 'N',
1744              'ń' => 'n',
1745              'Ņ' => 'N',
1746              'ņ' => 'n',
1747              'Ň' => 'N',
1748              'ň' => 'n',
1749              'ʼn' => 'n',
1750              'Ŋ' => 'N',
1751              'ŋ' => 'n',
1752              'Ō' => 'O',
1753              'ō' => 'o',
1754              'Ŏ' => 'O',
1755              'ŏ' => 'o',
1756              'Ő' => 'O',
1757              'ő' => 'o',
1758              'Œ' => 'OE',
1759              'œ' => 'oe',
1760              'Ŕ' => 'R',
1761              'ŕ' => 'r',
1762              'Ŗ' => 'R',
1763              'ŗ' => 'r',
1764              'Ř' => 'R',
1765              'ř' => 'r',
1766              'Ś' => 'S',
1767              'ś' => 's',
1768              'Ŝ' => 'S',
1769              'ŝ' => 's',
1770              'Ş' => 'S',
1771              'ş' => 's',
1772              'Š' => 'S',
1773              'š' => 's',
1774              'Ţ' => 'T',
1775              'ţ' => 't',
1776              'Ť' => 'T',
1777              'ť' => 't',
1778              'Ŧ' => 'T',
1779              'ŧ' => 't',
1780              'Ũ' => 'U',
1781              'ũ' => 'u',
1782              'Ū' => 'U',
1783              'ū' => 'u',
1784              'Ŭ' => 'U',
1785              'ŭ' => 'u',
1786              'Ů' => 'U',
1787              'ů' => 'u',
1788              'Ű' => 'U',
1789              'ű' => 'u',
1790              'Ų' => 'U',
1791              'ų' => 'u',
1792              'Ŵ' => 'W',
1793              'ŵ' => 'w',
1794              'Ŷ' => 'Y',
1795              'ŷ' => 'y',
1796              'Ÿ' => 'Y',
1797              'Ź' => 'Z',
1798              'ź' => 'z',
1799              'Ż' => 'Z',
1800              'ż' => 'z',
1801              'Ž' => 'Z',
1802              'ž' => 'z',
1803              'ſ' => 's',
1804              // Decompositions for Latin Extended-B.
1805              'Ș' => 'S',
1806              'ș' => 's',
1807              'Ț' => 'T',
1808              'ț' => 't',
1809              // Euro sign.
1810              '€' => 'E',
1811              // GBP (Pound) sign.
1812              '£' => '',
1813              // Vowels with diacritic (Vietnamese).
1814              // Unmarked.
1815              'Ơ' => 'O',
1816              'ơ' => 'o',
1817              'Ư' => 'U',
1818              'ư' => 'u',
1819              // Grave accent.
1820              'Ầ' => 'A',
1821              'ầ' => 'a',
1822              'Ằ' => 'A',
1823              'ằ' => 'a',
1824              'Ề' => 'E',
1825              'ề' => 'e',
1826              'Ồ' => 'O',
1827              'ồ' => 'o',
1828              'Ờ' => 'O',
1829              'ờ' => 'o',
1830              'Ừ' => 'U',
1831              'ừ' => 'u',
1832              'Ỳ' => 'Y',
1833              'ỳ' => 'y',
1834              // Hook.
1835              'Ả' => 'A',
1836              'ả' => 'a',
1837              'Ẩ' => 'A',
1838              'ẩ' => 'a',
1839              'Ẳ' => 'A',
1840              'ẳ' => 'a',
1841              'Ẻ' => 'E',
1842              'ẻ' => 'e',
1843              'Ể' => 'E',
1844              'ể' => 'e',
1845              'Ỉ' => 'I',
1846              'ỉ' => 'i',
1847              'Ỏ' => 'O',
1848              'ỏ' => 'o',
1849              'Ổ' => 'O',
1850              'ổ' => 'o',
1851              'Ở' => 'O',
1852              'ở' => 'o',
1853              'Ủ' => 'U',
1854              'ủ' => 'u',
1855              'Ử' => 'U',
1856              'ử' => 'u',
1857              'Ỷ' => 'Y',
1858              'ỷ' => 'y',
1859              // Tilde.
1860              'Ẫ' => 'A',
1861              'ẫ' => 'a',
1862              'Ẵ' => 'A',
1863              'ẵ' => 'a',
1864              'Ẽ' => 'E',
1865              'ẽ' => 'e',
1866              'Ễ' => 'E',
1867              'ễ' => 'e',
1868              'Ỗ' => 'O',
1869              'ỗ' => 'o',
1870              'Ỡ' => 'O',
1871              'ỡ' => 'o',
1872              'Ữ' => 'U',
1873              'ữ' => 'u',
1874              'Ỹ' => 'Y',
1875              'ỹ' => 'y',
1876              // Acute accent.
1877              'Ấ' => 'A',
1878              'ấ' => 'a',
1879              'Ắ' => 'A',
1880              'ắ' => 'a',
1881              'Ế' => 'E',
1882              'ế' => 'e',
1883              'Ố' => 'O',
1884              'ố' => 'o',
1885              'Ớ' => 'O',
1886              'ớ' => 'o',
1887              'Ứ' => 'U',
1888              'ứ' => 'u',
1889              // Dot below.
1890              'Ạ' => 'A',
1891              'ạ' => 'a',
1892              'Ậ' => 'A',
1893              'ậ' => 'a',
1894              'Ặ' => 'A',
1895              'ặ' => 'a',
1896              'Ẹ' => 'E',
1897              'ẹ' => 'e',
1898              'Ệ' => 'E',
1899              'ệ' => 'e',
1900              'Ị' => 'I',
1901              'ị' => 'i',
1902              'Ọ' => 'O',
1903              'ọ' => 'o',
1904              'Ộ' => 'O',
1905              'ộ' => 'o',
1906              'Ợ' => 'O',
1907              'ợ' => 'o',
1908              'Ụ' => 'U',
1909              'ụ' => 'u',
1910              'Ự' => 'U',
1911              'ự' => 'u',
1912              'Ỵ' => 'Y',
1913              'ỵ' => 'y',
1914              // Vowels with diacritic (Chinese, Hanyu Pinyin).
1915              'ɑ' => 'a',
1916              // Macron.
1917              'Ǖ' => 'U',
1918              'ǖ' => 'u',
1919              // Acute accent.
1920              'Ǘ' => 'U',
1921              'ǘ' => 'u',
1922              // Caron.
1923              'Ǎ' => 'A',
1924              'ǎ' => 'a',
1925              'Ǐ' => 'I',
1926              'ǐ' => 'i',
1927              'Ǒ' => 'O',
1928              'ǒ' => 'o',
1929              'Ǔ' => 'U',
1930              'ǔ' => 'u',
1931              'Ǚ' => 'U',
1932              'ǚ' => 'u',
1933              // Grave accent.
1934              'Ǜ' => 'U',
1935              'ǜ' => 'u',
1936          );
1937  
1938          // Used for locale-specific rules.
1939          $locale = get_locale();
1940  
1941          if ( 'de_DE' == $locale || 'de_DE_formal' == $locale || 'de_CH' == $locale || 'de_CH_informal' == $locale ) {
1942              $chars['Ä'] = 'Ae';
1943              $chars['ä'] = 'ae';
1944              $chars['Ö'] = 'Oe';
1945              $chars['ö'] = 'oe';
1946              $chars['Ü'] = 'Ue';
1947              $chars['ü'] = 'ue';
1948              $chars['ß'] = 'ss';
1949          } elseif ( 'da_DK' === $locale ) {
1950              $chars['Æ'] = 'Ae';
1951              $chars['æ'] = 'ae';
1952              $chars['Ø'] = 'Oe';
1953              $chars['ø'] = 'oe';
1954              $chars['Å'] = 'Aa';
1955              $chars['å'] = 'aa';
1956          } elseif ( 'ca' === $locale ) {
1957              $chars['l·l'] = 'll';
1958          } elseif ( 'sr_RS' === $locale || 'bs_BA' === $locale ) {
1959              $chars['Đ'] = 'DJ';
1960              $chars['đ'] = 'dj';
1961          }
1962  
1963          $string = strtr( $string, $chars );
1964      } else {
1965          $chars = array();
1966          // Assume ISO-8859-1 if not UTF-8.
1967          $chars['in'] = "\x80\x83\x8a\x8e\x9a\x9e"
1968              . "\x9f\xa2\xa5\xb5\xc0\xc1\xc2"
1969              . "\xc3\xc4\xc5\xc7\xc8\xc9\xca"
1970              . "\xcb\xcc\xcd\xce\xcf\xd1\xd2"
1971              . "\xd3\xd4\xd5\xd6\xd8\xd9\xda"
1972              . "\xdb\xdc\xdd\xe0\xe1\xe2\xe3"
1973              . "\xe4\xe5\xe7\xe8\xe9\xea\xeb"
1974              . "\xec\xed\xee\xef\xf1\xf2\xf3"
1975              . "\xf4\xf5\xf6\xf8\xf9\xfa\xfb"
1976              . "\xfc\xfd\xff";
1977  
1978          $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy';
1979  
1980          $string              = strtr( $string, $chars['in'], $chars['out'] );
1981          $double_chars        = array();
1982          $double_chars['in']  = array( "\x8c", "\x9c", "\xc6", "\xd0", "\xde", "\xdf", "\xe6", "\xf0", "\xfe" );
1983          $double_chars['out'] = array( 'OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th' );
1984          $string              = str_replace( $double_chars['in'], $double_chars['out'], $string );
1985      }
1986  
1987      return $string;
1988  }
1989  
1990  /**
1991   * Sanitizes a filename, replacing whitespace with dashes.
1992   *
1993   * Removes special characters that are illegal in filenames on certain
1994   * operating systems and special characters requiring special escaping
1995   * to manipulate at the command line. Replaces spaces and consecutive
1996   * dashes with a single dash. Trims period, dash and underscore from beginning
1997   * and end of filename. It is not guaranteed that this function will return a
1998   * filename that is allowed to be uploaded.
1999   *
2000   * @since 2.1.0
2001   *
2002   * @param string $filename The filename to be sanitized.
2003   * @return string The sanitized filename.
2004   */
2005  function sanitize_file_name( $filename ) {
2006      $filename_raw  = $filename;
2007      $special_chars = array( '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', "'", '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+', chr( 0 ) );
2008      /**
2009       * Filters the list of characters to remove from a filename.
2010       *
2011       * @since 2.8.0
2012       *
2013       * @param string[] $special_chars Array of characters to remove.
2014       * @param string   $filename_raw  The original filename to be sanitized.
2015       */
2016      $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
2017      $filename      = preg_replace( "#\x{00a0}#siu", ' ', $filename );
2018      $filename      = str_replace( $special_chars, '', $filename );
2019      $filename      = str_replace( array( '%20', '+' ), '-', $filename );
2020      $filename      = preg_replace( '/[\r\n\t -]+/', '-', $filename );
2021      $filename      = trim( $filename, '.-_' );
2022  
2023      if ( false === strpos( $filename, '.' ) ) {
2024          $mime_types = wp_get_mime_types();
2025          $filetype   = wp_check_filetype( 'test.' . $filename, $mime_types );
2026          if ( $filetype['ext'] === $filename ) {
2027              $filename = 'unnamed-file.' . $filetype['ext'];
2028          }
2029      }
2030  
2031      // Split the filename into a base and extension[s].
2032      $parts = explode( '.', $filename );
2033  
2034      // Return if only one extension.
2035      if ( count( $parts ) <= 2 ) {
2036          /**
2037           * Filters a sanitized filename string.
2038           *
2039           * @since 2.8.0
2040           *
2041           * @param string $filename     Sanitized filename.
2042           * @param string $filename_raw The filename prior to sanitization.
2043           */
2044          return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
2045      }
2046  
2047      // Process multiple extensions.
2048      $filename  = array_shift( $parts );
2049      $extension = array_pop( $parts );
2050      $mimes     = get_allowed_mime_types();
2051  
2052      /*
2053       * Loop over any intermediate extensions. Postfix them with a trailing underscore
2054       * if they are a 2 - 5 character long alpha string not in the extension whitelist.
2055       */
2056      foreach ( (array) $parts as $part ) {
2057          $filename .= '.' . $part;
2058  
2059          if ( preg_match( '/^[a-zA-Z]{2,5}\d?$/', $part ) ) {
2060              $allowed = false;
2061              foreach ( $mimes as $ext_preg => $mime_match ) {
2062                  $ext_preg = '!^(' . $ext_preg . ')$!i';
2063                  if ( preg_match( $ext_preg, $part ) ) {
2064                      $allowed = true;
2065                      break;
2066                  }
2067              }
2068              if ( ! $allowed ) {
2069                  $filename .= '_';
2070              }
2071          }
2072      }
2073      $filename .= '.' . $extension;
2074      /** This filter is documented in wp-includes/formatting.php */
2075      return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
2076  }
2077  
2078  /**
2079   * Sanitizes a username, stripping out unsafe characters.
2080   *
2081   * Removes tags, octets, entities, and if strict is enabled, will only keep
2082   * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
2083   * raw username (the username in the parameter), and the value of $strict as
2084   * parameters for the {@see 'sanitize_user'} filter.
2085   *
2086   * @since 2.0.0
2087   *
2088   * @param string $username The username to be sanitized.
2089   * @param bool   $strict   If set limits $username to specific characters. Default false.
2090   * @return string The sanitized username, after passing through filters.
2091   */
2092  function sanitize_user( $username, $strict = false ) {
2093      $raw_username = $username;
2094      $username     = wp_strip_all_tags( $username );
2095      $username     = remove_accents( $username );
2096      // Kill octets.
2097      $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
2098      // Kill entities.
2099      $username = preg_replace( '/&.+?;/', '', $username );
2100  
2101      // If strict, reduce to ASCII for max portability.
2102      if ( $strict ) {
2103          $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
2104      }
2105  
2106      $username = trim( $username );
2107      // Consolidate contiguous whitespace.
2108      $username = preg_replace( '|\s+|', ' ', $username );
2109  
2110      /**
2111       * Filters a sanitized username string.
2112       *
2113       * @since 2.0.1
2114       *
2115       * @param string $username     Sanitized username.
2116       * @param string $raw_username The username prior to sanitization.
2117       * @param bool   $strict       Whether to limit the sanitization to specific characters. Default false.
2118       */
2119      return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
2120  }
2121  
2122  /**
2123   * Sanitizes a string key.
2124   *
2125   * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
2126   *
2127   * @since 3.0.0
2128   *
2129   * @param string $key String key
2130   * @return string Sanitized key
2131   */
2132  function sanitize_key( $key ) {
2133      $raw_key = $key;
2134      $key     = strtolower( $key );
2135      $key     = preg_replace( '/[^a-z0-9_\-]/', '', $key );
2136  
2137      /**
2138       * Filters a sanitized key string.
2139       *
2140       * @since 3.0.0
2141       *
2142       * @param string $key     Sanitized key.
2143       * @param string $raw_key The key prior to sanitization.
2144       */
2145      return apply_filters( 'sanitize_key', $key, $raw_key );
2146  }
2147  
2148  /**
2149   * Sanitizes a title, or returns a fallback title.
2150   *
2151   * Specifically, HTML and PHP tags are stripped. Further actions can be added
2152   * via the plugin API. If $title is empty and $fallback_title is set, the latter
2153   * will be used.
2154   *
2155   * @since 1.0.0
2156   *
2157   * @param string $title          The string to be sanitized.
2158   * @param string $fallback_title Optional. A title to use if $title is empty.
2159   * @param string $context        Optional. The operation for which the string is sanitized
2160   * @return string The sanitized string.
2161   */
2162  function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
2163      $raw_title = $title;
2164  
2165      if ( 'save' == $context ) {
2166          $title = remove_accents( $title );
2167      }
2168  
2169      /**
2170       * Filters a sanitized title string.
2171       *
2172       * @since 1.2.0
2173       *
2174       * @param string $title     Sanitized title.
2175       * @param string $raw_title The title prior to sanitization.
2176       * @param string $context   The context for which the title is being sanitized.
2177       */
2178      $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
2179  
2180      if ( '' === $title || false === $title ) {
2181          $title = $fallback_title;
2182      }
2183  
2184      return $title;
2185  }
2186  
2187  /**
2188   * Sanitizes a title with the 'query' context.
2189   *
2190   * Used for querying the database for a value from URL.
2191   *
2192   * @since 3.1.0
2193   *
2194   * @param string $title The string to be sanitized.
2195   * @return string The sanitized string.
2196   */
2197  function sanitize_title_for_query( $title ) {
2198      return sanitize_title( $title, '', 'query' );
2199  }
2200  
2201  /**
2202   * Sanitizes a title, replacing whitespace and a few other characters with dashes.
2203   *
2204   * Limits the output to alphanumeric characters, underscore (_) and dash (-).
2205   * Whitespace becomes a dash.
2206   *
2207   * @since 1.2.0
2208   *
2209   * @param string $title     The title to be sanitized.
2210   * @param string $raw_title Optional. Not used.
2211   * @param string $context   Optional. The operation for which the string is sanitized.
2212   * @return string The sanitized title.
2213   */
2214  function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
2215      $title = strip_tags( $title );
2216      // Preserve escaped octets.
2217      $title = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title );
2218      // Remove percent signs that are not part of an octet.
2219      $title = str_replace( '%', '', $title );
2220      // Restore octets.
2221      $title = preg_replace( '|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title );
2222  
2223      if ( seems_utf8( $title ) ) {
2224          if ( function_exists( 'mb_strtolower' ) ) {
2225              $title = mb_strtolower( $title, 'UTF-8' );
2226          }
2227          $title = utf8_uri_encode( $title, 200 );
2228      }
2229  
2230      $title = strtolower( $title );
2231  
2232      if ( 'save' == $context ) {
2233          // Convert &nbsp, &ndash, and &mdash to hyphens.
2234          $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
2235          // Convert &nbsp, &ndash, and &mdash HTML entities to hyphens.
2236          $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', $title );
2237          // Convert forward slash to hyphen.
2238          $title = str_replace( '/', '-', $title );
2239  
2240          // Strip these characters entirely.
2241          $title = str_replace(
2242              array(
2243                  // Soft hyphens.
2244                  '%c2%ad',
2245                  // &iexcl and &iquest.
2246                  '%c2%a1',
2247                  '%c2%bf',
2248                  // Angle quotes.
2249                  '%c2%ab',
2250                  '%c2%bb',
2251                  '%e2%80%b9',
2252                  '%e2%80%ba',
2253                  // Curly quotes.
2254                  '%e2%80%98',
2255                  '%e2%80%99',
2256                  '%e2%80%9c',
2257                  '%e2%80%9d',
2258                  '%e2%80%9a',
2259                  '%e2%80%9b',
2260                  '%e2%80%9e',
2261                  '%e2%80%9f',
2262                  // &copy, &reg, &deg, &hellip, and &trade.
2263                  '%c2%a9',
2264                  '%c2%ae',
2265                  '%c2%b0',
2266                  '%e2%80%a6',
2267                  '%e2%84%a2',
2268                  // Acute accents.
2269                  '%c2%b4',
2270                  '%cb%8a',
2271                  '%cc%81',
2272                  '%cd%81',
2273                  // Grave accent, macron, caron.
2274                  '%cc%80',
2275                  '%cc%84',
2276                  '%cc%8c',
2277              ),
2278              '',
2279              $title
2280          );
2281  
2282          // Convert &times to 'x'.
2283          $title = str_replace( '%c3%97', 'x', $title );
2284      }
2285  
2286      // Kill entities.
2287      $title = preg_replace( '/&.+?;/', '', $title );
2288      $title = str_replace( '.', '-', $title );
2289  
2290      $title = preg_replace( '/[^%a-z0-9 _-]/', '', $title );
2291      $title = preg_replace( '/\s+/', '-', $title );
2292      $title = preg_replace( '|-+|', '-', $title );
2293      $title = trim( $title, '-' );
2294  
2295      return $title;
2296  }
2297  
2298  /**
2299   * Ensures a string is a valid SQL 'order by' clause.
2300   *
2301   * Accepts one or more columns, with or without a sort order (ASC / DESC).
2302   * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
2303   *
2304   * Also accepts 'RAND()'.
2305   *
2306   * @since 2.5.1
2307   *
2308   * @param string $orderby Order by clause to be validated.
2309   * @return string|false Returns $orderby if valid, false otherwise.
2310   */
2311  function sanitize_sql_orderby( $orderby ) {
2312      if ( preg_match( '/^\s*(([a-z0-9_]+|`[a-z0-9_]+`)(\s+(ASC|DESC))?\s*(,\s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^\s*RAND\(\s*\)\s*$/i', $orderby ) ) {
2313          return $orderby;
2314      }
2315      return false;
2316  }
2317  
2318  /**
2319   * Sanitizes an HTML classname to ensure it only contains valid characters.
2320   *
2321   * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
2322   * string then it will return the alternative value supplied.
2323   *
2324   * @todo Expand to support the full range of CDATA that a class attribute can contain.
2325   *
2326   * @since 2.8.0
2327   *
2328   * @param string $class    The classname to be sanitized
2329   * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
2330   *  Defaults to an empty string.
2331   * @return string The sanitized value
2332   */
2333  function sanitize_html_class( $class, $fallback = '' ) {
2334      // Strip out any %-encoded octets.
2335      $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
2336  
2337      // Limit to A-Z, a-z, 0-9, '_', '-'.
2338      $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
2339  
2340      if ( '' == $sanitized && $fallback ) {
2341          return sanitize_html_class( $fallback );
2342      }
2343      /**
2344       * Filters a sanitized HTML class string.
2345       *
2346       * @since 2.8.0
2347       *
2348       * @param string $sanitized The sanitized HTML class.
2349       * @param string $class     HTML class before sanitization.
2350       * @param string $fallback  The fallback string.
2351       */
2352      return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
2353  }
2354  
2355  /**
2356   * Converts lone & characters into `&#038;` (a.k.a. `&amp;`)
2357   *
2358   * @since 0.71
2359   *
2360   * @param string $content    String of characters to be converted.
2361   * @param string $deprecated Not used.
2362   * @return string Converted string.
2363   */
2364  function convert_chars( $content, $deprecated = '' ) {
2365      if ( ! empty( $deprecated ) ) {
2366          _deprecated_argument( __FUNCTION__, '0.71' );
2367      }
2368  
2369      if ( strpos( $content, '&' ) !== false ) {
2370          $content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content );
2371      }
2372  
2373      return $content;
2374  }
2375  
2376  /**
2377   * Converts invalid Unicode references range to valid range.
2378   *
2379   * @since 4.3.0
2380   *
2381   * @param string $content String with entities that need converting.
2382   * @return string Converted string.
2383   */
2384  function convert_invalid_entities( $content ) {
2385      $wp_htmltranswinuni = array(
2386          '&#128;' => '&#8364;', // The Euro sign.
2387          '&#129;' => '',
2388          '&#130;' => '&#8218;', // These are Windows CP1252 specific characters.
2389          '&#131;' => '&#402;',  // They would look weird on non-Windows browsers.
2390          '&#132;' => '&#8222;',
2391          '&#133;' => '&#8230;',
2392          '&#134;' => '&#8224;',
2393          '&#135;' => '&#8225;',
2394          '&#136;' => '&#710;',
2395          '&#137;' => '&#8240;',
2396          '&#138;' => '&#352;',
2397          '&#139;' => '&#8249;',
2398          '&#140;' => '&#338;',
2399          '&#141;' => '',
2400          '&#142;' => '&#381;',
2401          '&#143;' => '',
2402          '&#144;' => '',
2403          '&#145;' => '&#8216;',
2404          '&#146;' => '&#8217;',
2405          '&#147;' => '&#8220;',
2406          '&#148;' => '&#8221;',
2407          '&#149;' => '&#8226;',
2408          '&#150;' => '&#8211;',
2409          '&#151;' => '&#8212;',
2410          '&#152;' => '&#732;',
2411          '&#153;' => '&#8482;',
2412          '&#154;' => '&#353;',
2413          '&#155;' => '&#8250;',
2414          '&#156;' => '&#339;',
2415          '&#157;' => '',
2416          '&#158;' => '&#382;',
2417          '&#159;' => '&#376;',
2418      );
2419  
2420      if ( strpos( $content, '&#1' ) !== false ) {
2421          $content = strtr( $content, $wp_htmltranswinuni );
2422      }
2423  
2424      return $content;
2425  }
2426  
2427  /**
2428   * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
2429   *
2430   * @since 0.71
2431   *
2432   * @param string $text  Text to be balanced
2433   * @param bool   $force If true, forces balancing, ignoring the value of the option. Default false.
2434   * @return string Balanced text
2435   */
2436  function balanceTags( $text, $force = false ) {  // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
2437      if ( $force || (int) get_option( 'use_balanceTags' ) === 1 ) {
2438          return force_balance_tags( $text );
2439      } else {
2440          return $text;
2441      }
2442  }
2443  
2444  /**
2445   * Balances tags of string using a modified stack.
2446   *
2447   * @since 2.0.4
2448   * @since 5.3.0 Improve accuracy and add support for custom element tags.
2449   *
2450   * @author Leonard Lin <leonard@acm.org>
2451   * @license GPL
2452   * @copyright November 4, 2001
2453   * @version 1.1
2454   * @todo Make better - change loop condition to $text in 1.2
2455   * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
2456   *      1.1  Fixed handling of append/stack pop order of end text
2457   *           Added Cleaning Hooks
2458   *      1.0  First Version
2459   *
2460   * @param string $text Text to be balanced.
2461   * @return string Balanced text.
2462   */
2463  function force_balance_tags( $text ) {
2464      $tagstack  = array();
2465      $stacksize = 0;
2466      $tagqueue  = '';
2467      $newtext   = '';
2468      // Known single-entity/self-closing tags.
2469      $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
2470      // Tags that can be immediately nested within themselves.
2471      $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
2472  
2473      // WP bug fix for comments - in case you REALLY meant to type '< !--'.
2474      $text = str_replace( '< !--', '<    !--', $text );
2475      // WP bug fix for LOVE <3 (and other situations with '<' before a number).
2476      $text = preg_replace( '#<([0-9]{1})#', '&lt;$1', $text );
2477  
2478      /**
2479       * Matches supported tags.
2480       *
2481       * To get the pattern as a string without the comments paste into a PHP
2482       * REPL like `php -a`.
2483       *
2484       * @see https://html.spec.whatwg.org/#elements-2
2485       * @see https://w3c.github.io/webcomponents/spec/custom/#valid-custom-element-name
2486       *
2487       * @example
2488       * ~# php -a
2489       * php > $s = [paste copied contents of expression below including parentheses];
2490       * php > echo $s;
2491       */
2492      $tag_pattern = (
2493          '#<' . // Start with an opening bracket.
2494          '(/?)' . // Group 1 - If it's a closing tag it'll have a leading slash.
2495          '(' . // Group 2 - Tag name.
2496              // Custom element tags have more lenient rules than HTML tag names.
2497              '(?:[a-z](?:[a-z0-9._]*)-(?:[a-z0-9._-]+)+)' .
2498                  '|' .
2499              // Traditional tag rules approximate HTML tag names.
2500              '(?:[\w:]+)' .
2501          ')' .
2502          '(?:' .
2503              // We either immediately close the tag with its '>' and have nothing here.
2504              '\s*' .
2505              '(/?)' . // Group 3 - "attributes" for empty tag.
2506                  '|' .
2507              // Or we must start with space characters to separate the tag name from the attributes (or whitespace).
2508              '(\s+)' . // Group 4 - Pre-attribute whitespace.
2509              '([^>]*)' . // Group 5 - Attributes.
2510          ')' .
2511          '>#' // End with a closing bracket.
2512      );
2513  
2514      while ( preg_match( $tag_pattern, $text, $regex ) ) {
2515          $full_match        = $regex[0];
2516          $has_leading_slash = ! empty( $regex[1] );
2517          $tag_name          = $regex[2];
2518          $tag               = strtolower( $tag_name );
2519          $is_single_tag     = in_array( $tag, $single_tags, true );
2520          $pre_attribute_ws  = isset( $regex[4] ) ? $regex[4] : '';
2521          $attributes        = trim( isset( $regex[5] ) ? $regex[5] : $regex[3] );
2522          $has_self_closer   = '/' === substr( $attributes, -1 );
2523  
2524          $newtext .= $tagqueue;
2525  
2526          $i = strpos( $text, $full_match );
2527          $l = strlen( $full_match );
2528  
2529          // Clear the shifter.
2530          $tagqueue = '';
2531          if ( $has_leading_slash ) { // End tag.
2532              // If too many closing tags.
2533              if ( $stacksize <= 0 ) {
2534                  $tag = '';
2535                  // Or close to be safe $tag = '/' . $tag.
2536  
2537                  // If stacktop value = tag close value, then pop.
2538              } elseif ( $tagstack[ $stacksize - 1 ] === $tag ) { // Found closing tag.
2539                  $tag = '</' . $tag . '>'; // Close tag.
2540                  array_pop( $tagstack );
2541                  $stacksize--;
2542              } else { // Closing tag not at top, search for it.
2543                  for ( $j = $stacksize - 1; $j >= 0; $j-- ) {
2544                      if ( $tagstack[ $j ] === $tag ) {
2545                          // Add tag to tagqueue.
2546                          for ( $k = $stacksize - 1; $k >= $j; $k-- ) {
2547                              $tagqueue .= '</' . array_pop( $tagstack ) . '>';
2548                              $stacksize--;
2549                          }
2550                          break;
2551                      }
2552                  }
2553                  $tag = '';
2554              }
2555          } else { // Begin tag.
2556              if ( $has_self_closer ) { // If it presents itself as a self-closing tag...
2557                  // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such
2558                  // and immediately close it with a closing tag (the tag will encapsulate no text as a result).
2559                  if ( ! $is_single_tag ) {
2560                      $attributes = trim( substr( $attributes, 0, -1 ) ) . "></$tag";
2561                  }
2562              } elseif ( $is_single_tag ) { // Else if it's a known single-entity tag but it doesn't close itself, do so.
2563                  $pre_attribute_ws = ' ';
2564                  $attributes      .= '/';
2565              } else { // It's not a single-entity tag.
2566                  // If the top of the stack is the same as the tag we want to push, close previous tag.
2567                  if ( $stacksize > 0 && ! in_array( $tag, $nestable_tags, true ) && $tagstack[ $stacksize - 1 ] === $tag ) {
2568                      $tagqueue = '</' . array_pop( $tagstack ) . '>';
2569                      $stacksize--;
2570                  }
2571                  $stacksize = array_push( $tagstack, $tag );
2572              }
2573  
2574              // Attributes.
2575              if ( $has_self_closer && $is_single_tag ) {
2576                  // We need some space - avoid <br/> and prefer <br />.
2577                  $pre_attribute_ws = ' ';
2578              }
2579  
2580              $tag = '<' . $tag . $pre_attribute_ws . $attributes . '>';
2581              // If already queuing a close tag, then put this tag on too.
2582              if ( ! empty( $tagqueue ) ) {
2583                  $tagqueue .= $tag;
2584                  $tag       = '';
2585              }
2586          }
2587          $newtext .= substr( $text, 0, $i ) . $tag;
2588          $text     = substr( $text, $i + $l );
2589      }
2590  
2591      // Clear tag queue.
2592      $newtext .= $tagqueue;
2593  
2594      // Add remaining text.
2595      $newtext .= $text;
2596  
2597      while ( $x = array_pop( $tagstack ) ) {
2598          $newtext .= '</' . $x . '>'; // Add remaining tags to close.
2599      }
2600  
2601      // WP fix for the bug with HTML comments.
2602      $newtext = str_replace( '< !--', '<!--', $newtext );
2603      $newtext = str_replace( '<    !--', '< !--', $newtext );
2604  
2605      return $newtext;
2606  }
2607  
2608  /**
2609   * Acts on text which is about to be edited.
2610   *
2611   * The $content is run through esc_textarea(), which uses htmlspecialchars()
2612   * to convert special characters to HTML entities. If `$richedit` is set to true,
2613   * it is simply a holder for the {@see 'format_to_edit'} filter.
2614   *
2615   * @since 0.71
2616   * @since 4.4.0 The `$richedit` parameter was renamed to `$rich_text` for clarity.
2617   *
2618   * @param string $content   The text about to be edited.
2619   * @param bool   $rich_text Optional. Whether `$content` should be considered rich text,
2620   *                          in which case it would not be passed through esc_textarea().
2621   *                          Default false.
2622   * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
2623   */
2624  function format_to_edit( $content, $rich_text = false ) {
2625      /**
2626       * Filters the text to be formatted for editing.
2627       *
2628       * @since 1.2.0
2629       *
2630       * @param string $content The text, prior to formatting for editing.
2631       */
2632      $content = apply_filters( 'format_to_edit', $content );
2633      if ( ! $rich_text ) {
2634          $content = esc_textarea( $content );
2635      }
2636      return $content;
2637  }
2638  
2639  /**
2640   * Add leading zeros when necessary.
2641   *
2642   * If you set the threshold to '4' and the number is '10', then you will get
2643   * back '0010'. If you set the threshold to '4' and the number is '5000', then you
2644   * will get back '5000'.
2645   *
2646   * Uses sprintf to append the amount of zeros based on the $threshold parameter
2647   * and the size of the number. If the number is large enough, then no zeros will
2648   * be appended.
2649   *
2650   * @since 0.71
2651   *
2652   * @param int $number     Number to append zeros to if not greater than threshold.
2653   * @param int $threshold  Digit places number needs to be to not have zeros added.
2654   * @return string Adds leading zeros to number if needed.
2655   */
2656  function zeroise( $number, $threshold ) {
2657      return sprintf( '%0' . $threshold . 's', $number );
2658  }
2659  
2660  /**
2661   * Adds backslashes before letters and before a number at the start of a string.
2662   *
2663   * @since 0.71
2664   *
2665   * @param string $string Value to which backslashes will be added.
2666   * @return string String with backslashes inserted.
2667   */
2668  function backslashit( $string ) {
2669      if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' ) {
2670          $string = '\\\\' . $string;
2671      }
2672      return addcslashes( $string, 'A..Za..z' );
2673  }
2674  
2675  /**
2676   * Appends a trailing slash.
2677   *
2678   * Will remove trailing forward and backslashes if it exists already before adding
2679   * a trailing forward slash. This prevents double slashing a string or path.
2680   *
2681   * The primary use of this is for paths and thus should be used for paths. It is
2682   * not restricted to paths and offers no specific path support.
2683   *
2684   * @since 1.2.0
2685   *
2686   * @param string $string What to add the trailing slash to.
2687   * @return string String with trailing slash added.
2688   */
2689  function trailingslashit( $string ) {
2690      return untrailingslashit( $string ) . '/';
2691  }
2692  
2693  /**
2694   * Removes trailing forward slashes and backslashes if they exist.
2695   *
2696   * The primary use of this is for paths and thus should be used for paths. It is
2697   * not restricted to paths and offers no specific path support.
2698   *
2699   * @since 2.2.0
2700   *
2701   * @param string $string What to remove the trailing slashes from.
2702   * @return string String without the trailing slashes.
2703   */
2704  function untrailingslashit( $string ) {
2705      return rtrim( $string, '/\\' );
2706  }
2707  
2708  /**
2709   * Adds slashes to escape strings.
2710   *
2711   * Slashes will first be removed if magic_quotes_gpc is set, see {@link
2712   * https://www.php.net/magic_quotes} for more details.
2713   *
2714   * @since 0.71
2715   *
2716   * @param string $gpc The string returned from HTTP request data.
2717   * @return string Returns a string escaped with slashes.
2718   */
2719  function addslashes_gpc( $gpc ) {
2720      return wp_slash( $gpc );
2721  }
2722  
2723  /**
2724   * Navigates through an array, object, or scalar, and removes slashes from the values.
2725   *
2726   * @since 2.0.0
2727   *
2728   * @param mixed $value The value to be stripped.
2729   * @return mixed Stripped value.
2730   */
2731  function stripslashes_deep( $value ) {
2732      return map_deep( $value, 'stripslashes_from_strings_only' );
2733  }
2734  
2735  /**
2736   * Callback function for `stripslashes_deep()` which strips slashes from strings.
2737   *
2738   * @since 4.4.0
2739   *
2740   * @param mixed $value The array or string to be stripped.
2741   * @return mixed $value The stripped value.
2742   */
2743  function stripslashes_from_strings_only( $value ) {
2744      return is_string( $value ) ? stripslashes( $value ) : $value;
2745  }
2746  
2747  /**
2748   * Navigates through an array, object, or scalar, and encodes the values to be used in a URL.
2749   *
2750   * @since 2.2.0
2751   *
2752   * @param mixed $value The array or string to be encoded.
2753   * @return mixed $value The encoded value.
2754   */
2755  function urlencode_deep( $value ) {
2756      return map_deep( $value, 'urlencode' );
2757  }
2758  
2759  /**
2760   * Navigates through an array, object, or scalar, and raw-encodes the values to be used in a URL.
2761   *
2762   * @since 3.4.0
2763   *
2764   * @param mixed $value The array or string to be encoded.
2765   * @return mixed $value The encoded value.
2766   */
2767  function rawurlencode_deep( $value ) {
2768      return map_deep( $value, 'rawurlencode' );
2769  }
2770  
2771  /**
2772   * Navigates through an array, object, or scalar, and decodes URL-encoded values
2773   *
2774   * @since 4.4.0
2775   *
2776   * @param mixed $value The array or string to be decoded.
2777   * @return mixed $value The decoded value.
2778   */
2779  function urldecode_deep( $value ) {
2780      return map_deep( $value, 'urldecode' );
2781  }
2782  
2783  /**
2784   * Converts email addresses characters to HTML entities to block spam bots.
2785   *
2786   * @since 0.71
2787   *
2788   * @param string $email_address Email address.
2789   * @param int    $hex_encoding  Optional. Set to 1 to enable hex encoding.
2790   * @return string Converted email address.
2791   */
2792  function antispambot( $email_address, $hex_encoding = 0 ) {
2793      $email_no_spam_address = '';
2794      for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
2795          $j = rand( 0, 1 + $hex_encoding );
2796          if ( 0 == $j ) {
2797              $email_no_spam_address .= '&#' . ord( $email_address[ $i ] ) . ';';
2798          } elseif ( 1 == $j ) {
2799              $email_no_spam_address .= $email_address[ $i ];
2800          } elseif ( 2 == $j ) {
2801              $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[ $i ] ) ), 2 );
2802          }
2803      }
2804  
2805      return str_replace( '@', '&#64;', $email_no_spam_address );
2806  }
2807  
2808  /**
2809   * Callback to convert URI match to HTML A element.
2810   *
2811   * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
2812   *
2813   * @since 2.3.2
2814   * @access private
2815   *
2816   * @param array $matches Single Regex Match.
2817   * @return string HTML A element with URI address.
2818   */
2819  function _make_url_clickable_cb( $matches ) {
2820      $url = $matches[2];
2821  
2822      if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
2823          // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it,
2824          // add the closing parenthesis to the URL. Then we can let the parenthesis balancer do its thing below.
2825          $url   .= $matches[3];
2826          $suffix = '';
2827      } else {
2828          $suffix = $matches[3];
2829      }
2830  
2831      // Include parentheses in the URL only if paired.
2832      while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
2833          $suffix = strrchr( $url, ')' ) . $suffix;
2834          $url    = substr( $url, 0, strrpos( $url, ')' ) );
2835      }
2836  
2837      $url = esc_url( $url );
2838      if ( empty( $url ) ) {
2839          return $matches[0];
2840      }
2841  
2842      if ( 'comment_text' === current_filter() ) {
2843          $rel = 'nofollow ugc';
2844      } else {
2845          $rel = 'nofollow';
2846      }
2847  
2848      /**
2849       * Filters the rel value that is added to URL matches converted to links.
2850       *
2851       * @since 5.3.0
2852       *
2853       * @param string $rel The rel value.
2854       * @param string $url The matched URL being converted to a link tag.
2855       */
2856      $rel = apply_filters( 'make_clickable_rel', $rel, $url );
2857      $rel = esc_attr( $rel );
2858  
2859      return $matches[1] . "<a href=\"$url\" rel=\"$rel\">$url</a>" . $suffix;
2860  }
2861  
2862  /**
2863   * Callback to convert URL match to HTML A element.
2864   *
2865   * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
2866   *
2867   * @since 2.3.2
2868   * @access private
2869   *
2870   * @param array $matches Single Regex Match.
2871   * @return string HTML A element with URL address.
2872   */
2873  function _make_web_ftp_clickable_cb( $matches ) {
2874      $ret  = '';
2875      $dest = $matches[2];
2876      $dest = 'http://' . $dest;
2877  
2878      // Removed trailing [.,;:)] from URL.
2879      $last_char = substr( $dest, -1 );
2880      if ( in_array( $last_char, array( '.', ',', ';', ':', ')' ), true ) === true ) {
2881          $ret  = $last_char;
2882          $dest = substr( $dest, 0, strlen( $dest ) - 1 );
2883      }
2884  
2885      $dest = esc_url( $dest );
2886      if ( empty( $dest ) ) {
2887          return $matches[0];
2888      }
2889  
2890      if ( 'comment_text' === current_filter() ) {
2891          $rel = 'nofollow ugc';
2892      } else {
2893          $rel = 'nofollow';
2894      }
2895  
2896      /** This filter is documented in wp-includes/formatting.php */
2897      $rel = apply_filters( 'make_clickable_rel', $rel, $dest );
2898      $rel = esc_attr( $rel );
2899  
2900      return $matches[1] . "<a href=\"$dest\" rel=\"$rel\">$dest</a>$ret";
2901  }
2902  
2903  /**
2904   * Callback to convert email address match to HTML A element.
2905   *
2906   * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
2907   *
2908   * @since 2.3.2
2909   * @access private
2910   *
2911   * @param array $matches Single Regex Match.
2912   * @return string HTML A element with email address.
2913   */
2914  function _make_email_clickable_cb( $matches ) {
2915      $email = $matches[2] . '@' . $matches[3];
2916      return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
2917  }
2918  
2919  /**
2920   * Convert plaintext URI to HTML links.
2921   *
2922   * Converts URI, www and ftp, and email addresses. Finishes by fixing links
2923   * within links.
2924   *
2925   * @since 0.71
2926   *
2927   * @param string $text Content to convert URIs.
2928   * @return string Content with converted URIs.
2929   */
2930  function make_clickable( $text ) {
2931      $r               = '';
2932      $textarr         = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // Split out HTML tags.
2933      $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>.
2934      foreach ( $textarr as $piece ) {
2935  
2936          if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) || preg_match( '|^<script[\s>]|i', $piece ) || preg_match( '|^<style[\s>]|i', $piece ) ) {
2937              $nested_code_pre++;
2938          } elseif ( $nested_code_pre && ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) || '</script>' === strtolower( $piece ) || '</style>' === strtolower( $piece ) ) ) {
2939              $nested_code_pre--;
2940          }
2941  
2942          if ( $nested_code_pre || empty( $piece ) || ( '<' === $piece[0] && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
2943              $r .= $piece;
2944              continue;
2945          }
2946  
2947          // Long strings might contain expensive edge cases...
2948          if ( 10000 < strlen( $piece ) ) {
2949              // ...break it up.
2950              foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses.
2951                  if ( 2101 < strlen( $chunk ) ) {
2952                      $r .= $chunk; // Too big, no whitespace: bail.
2953                  } else {
2954                      $r .= make_clickable( $chunk );
2955                  }
2956              }
2957          } else {
2958              $ret = " $piece "; // Pad with whitespace to simplify the regexes.
2959  
2960              $url_clickable = '~
2961                  ([\\s(<.,;:!?])                                # 1: Leading whitespace, or punctuation.
2962                  (                                              # 2: URL.
2963                      [\\w]{1,20}+://                                # Scheme and hier-part prefix.
2964                      (?=\S{1,2000}\s)                               # Limit to URLs less than about 2000 characters long.
2965                      [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+         # Non-punctuation URL character.
2966                      (?:                                            # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character.
2967                          [\'.,;:!?)]                                    # Punctuation URL character.
2968                          [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++         # Non-punctuation URL character.
2969                      )*
2970                  )
2971                  (\)?)                                          # 3: Trailing closing parenthesis (for parethesis balancing post processing).
2972              ~xS';
2973              // The regex is a non-anchored pattern and does not have a single fixed starting character.
2974              // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
2975  
2976              $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
2977  
2978              $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
2979              $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
2980  
2981              $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
2982              $r  .= $ret;
2983          }
2984      }
2985  
2986      // Cleanup of accidental links within links.
2987      return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', '$1$3</a>', $r );
2988  }
2989  
2990  /**
2991   * Breaks a string into chunks by splitting at whitespace characters.
2992   * The length of each returned chunk is as close to the specified length goal as possible,
2993   * with the caveat that each chunk includes its trailing delimiter.
2994   * Chunks longer than the goal are guaranteed to not have any inner whitespace.
2995   *
2996   * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
2997   *
2998   * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
2999   *
3000   *     _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234   890 123456789 1234567890a    45678   1 3 5 7 90 ", 10 ) ==
3001   *     array (
3002   *         0 => '1234 67890 ',  // 11 characters: Perfect split.
3003   *         1 => '1234 ',        //  5 characters: '1234 67890a' was too long.
3004   *         2 => '67890a cd ',   // 10 characters: '67890a cd 1234' was too long.
3005   *         3 => '1234   890 ',  // 11 characters: Perfect split.
3006   *         4 => '123456789 ',   // 10 characters: '123456789 1234567890a' was too long.
3007   *         5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split.
3008   *         6 => '   45678   ',  // 11 characters: Perfect split.
3009   *         7 => '1 3 5 7 90 ',  // 11 characters: End of $string.
3010   *     );
3011   *
3012   * @since 3.4.0
3013   * @access private
3014   *
3015   * @param string $string The string to split.
3016   * @param int    $goal   The desired chunk length.
3017   * @return array Numeric array of chunks.
3018   */
3019  function _split_str_by_whitespace( $string, $goal ) {
3020      $chunks = array();
3021  
3022      $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
3023  
3024      while ( $goal < strlen( $string_nullspace ) ) {
3025          $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
3026  
3027          if ( false === $pos ) {
3028              $pos = strpos( $string_nullspace, "\000", $goal + 1 );
3029              if ( false === $pos ) {
3030                  break;
3031              }
3032          }
3033  
3034          $chunks[]         = substr( $string, 0, $pos + 1 );
3035          $string           = substr( $string, $pos + 1 );
3036          $string_nullspace = substr( $string_nullspace, $pos + 1 );
3037      }
3038  
3039      if ( $string ) {
3040          $chunks[] = $string;
3041      }
3042  
3043      return $chunks;
3044  }
3045  
3046  /**
3047   * Callback to add a rel attribute to HTML A element.
3048   *
3049   * Will remove already existing string before adding to prevent invalidating (X)HTML.
3050   *
3051   * @since 5.3.0
3052   *
3053   * @param array  $matches Single match.
3054   * @param string $rel     The rel attribute to add.
3055   * @return string HTML A element with the added rel attribute.
3056   */
3057  function wp_rel_callback( $matches, $rel ) {
3058      $text = $matches[1];
3059      $atts = wp_kses_hair( $matches[1], wp_allowed_protocols() );
3060  
3061      if ( ! empty( $atts['href'] ) ) {
3062          if ( in_array( strtolower( wp_parse_url( $atts['href']['value'], PHP_URL_SCHEME ) ), array( 'http', 'https' ), true ) ) {
3063              if ( strtolower( wp_parse_url( $atts['href']['value'], PHP_URL_HOST ) ) === strtolower( wp_parse_url( home_url(), PHP_URL_HOST ) ) ) {
3064                  return "<a $text>";
3065              }
3066          }
3067      }
3068  
3069      if ( ! empty( $atts['rel'] ) ) {
3070          $parts     = array_map( 'trim', explode( ' ', $atts['rel']['value'] ) );
3071          $rel_array = array_map( 'trim', explode( ' ', $rel ) );
3072          $parts     = array_unique( array_merge( $parts, $rel_array ) );
3073          $rel       = implode( ' ', $parts );
3074          unset( $atts['rel'] );
3075  
3076          $html = '';
3077          foreach ( $atts as $name => $value ) {
3078              if ( isset( $value['vless'] ) && 'y' === $value['vless'] ) {
3079                  $html .= $name . ' ';
3080              } else {
3081                  $html .= "{$name}=\"" . esc_attr( $value['value'] ) . '" ';
3082              }
3083          }
3084          $text = trim( $html );
3085      }
3086      return "<a $text rel=\"" . esc_attr( $rel ) . '">';
3087  }
3088  
3089  /**
3090   * Adds `rel="nofollow"` string to all HTML A elements in content.
3091   *
3092   * @since 1.5.0
3093   *
3094   * @param string $text Content that may contain HTML A elements.
3095   * @return string Converted content.
3096   */
3097  function wp_rel_nofollow( $text ) {
3098      // This is a pre-save filter, so text is already escaped.
3099      $text = stripslashes( $text );
3100      $text = preg_replace_callback(
3101          '|<a (.+?)>|i',
3102          function( $matches ) {
3103              return wp_rel_callback( $matches, 'nofollow' );
3104          },
3105          $text
3106      );
3107      return wp_slash( $text );
3108  }
3109  
3110  /**
3111   * Callback to add `rel="nofollow"` string to HTML A element.
3112   *
3113   * @since 2.3.0
3114   * @deprecated 5.3.0 Use wp_rel_callback()
3115   *
3116   * @param array $matches Single match.
3117   * @return string HTML A Element with `rel="nofollow"`.
3118   */
3119  function wp_rel_nofollow_callback( $matches ) {
3120      return wp_rel_callback( $matches, 'nofollow' );
3121  }
3122  
3123  /**
3124   * Adds `rel="nofollow ugc"` string to all HTML A elements in content.
3125   *
3126   * @since 5.3.0
3127   *
3128   * @param string $text Content that may contain HTML A elements.
3129   * @return string Converted content.
3130   */
3131  function wp_rel_ugc( $text ) {
3132      // This is a pre-save filter, so text is already escaped.
3133      $text = stripslashes( $text );
3134      $text = preg_replace_callback(
3135          '|<a (.+?)>|i',
3136          function( $matches ) {
3137              return wp_rel_callback( $matches, 'nofollow ugc' );
3138          },
3139          $text
3140      );
3141      return wp_slash( $text );
3142  }
3143  
3144  /**
3145   * Adds rel noreferrer and noopener to all HTML A elements that have a target.
3146   *
3147   * @since 5.1.0
3148   *
3149   * @param string $text Content that may contain HTML A elements.
3150   * @return string Converted content.
3151   */
3152  function wp_targeted_link_rel( $text ) {
3153      // Don't run (more expensive) regex if no links with targets.
3154      if ( stripos( $text, 'target' ) === false || stripos( $text, '<a ' ) === false || is_serialized( $text ) ) {
3155          return $text;
3156      }
3157  
3158      $script_and_style_regex = '/<(script|style).*?<\/\\1>/si';
3159  
3160      preg_match_all( $script_and_style_regex, $text, $matches );
3161      $extra_parts = $matches[0];
3162      $html_parts  = preg_split( $script_and_style_regex, $text );
3163  
3164      foreach ( $html_parts as &$part ) {
3165          $part = preg_replace_callback( '|<a\s([^>]*target\s*=[^>]*)>|i', 'wp_targeted_link_rel_callback', $part );
3166      }
3167  
3168      $text = '';
3169      for ( $i = 0; $i < count( $html_parts ); $i++ ) {
3170          $text .= $html_parts[ $i ];
3171          if ( isset( $extra_parts[ $i ] ) ) {
3172              $text .= $extra_parts[ $i ];
3173          }
3174      }
3175  
3176      return $text;
3177  }
3178  
3179  /**
3180   * Callback to add rel="noreferrer noopener" string to HTML A element.
3181   *
3182   * Will not duplicate existing noreferrer and noopener values
3183   * to prevent from invalidating the HTML.
3184   *
3185   * @since 5.1.0
3186   *
3187   * @param array $matches Single Match
3188   * @return string HTML A Element with rel noreferrer noopener in addition to any existing values
3189   */
3190  function wp_targeted_link_rel_callback( $matches ) {
3191      $link_html          = $matches[1];
3192      $original_link_html = $link_html;
3193  
3194      // Consider the HTML escaped if there are no unescaped quotes.
3195      $is_escaped = ! preg_match( '/(^|[^\\\\])[\'"]/', $link_html );
3196      if ( $is_escaped ) {
3197          // Replace only the quotes so that they are parsable by wp_kses_hair(), leave the rest as is.
3198          $link_html = preg_replace( '/\\\\([\'"])/', '$1', $link_html );
3199      }
3200  
3201      $atts = wp_kses_hair( $link_html, wp_allowed_protocols() );
3202  
3203      /**
3204       * Filters the rel values that are added to links with `target` attribute.
3205       *
3206       * @since 5.1.0
3207       *
3208       * @param string $rel       The rel values.
3209       * @param string $link_html The matched content of the link tag including all HTML attributes.
3210       */
3211      $rel = apply_filters( 'wp_targeted_link_rel', 'noopener noreferrer', $link_html );
3212  
3213      // Return early if no rel values to be added or if no actual target attribute.
3214      if ( ! $rel || ! isset( $atts['target'] ) ) {
3215          return "<a $original_link_html>";
3216      }
3217  
3218      if ( isset( $atts['rel'] ) ) {
3219          $all_parts = preg_split( '/\s/', "{$atts['rel']['value']} $rel", -1, PREG_SPLIT_NO_EMPTY );
3220          $rel       = implode( ' ', array_unique( $all_parts ) );
3221      }
3222  
3223      $atts['rel']['whole'] = 'rel="' . esc_attr( $rel ) . '"';
3224      $link_html            = join( ' ', array_column( $atts, 'whole' ) );
3225  
3226      if ( $is_escaped ) {
3227          $link_html = preg_replace( '/[\'"]/', '\\\\$0', $link_html );
3228      }
3229  
3230      return "<a $link_html>";
3231  }
3232  
3233  /**
3234   * Adds all filters modifying the rel attribute of targeted links.
3235   *
3236   * @since 5.1.0
3237   */
3238  function wp_init_targeted_link_rel_filters() {
3239      $filters = array(
3240          'title_save_pre',
3241          'content_save_pre',
3242          'excerpt_save_pre',
3243          'content_filtered_save_pre',
3244          'pre_comment_content',
3245          'pre_term_description',
3246          'pre_link_description',
3247          'pre_link_notes',
3248          'pre_user_description',
3249      );
3250  
3251      foreach ( $filters as $filter ) {
3252          add_filter( $filter, 'wp_targeted_link_rel' );
3253      };
3254  }
3255  
3256  /**
3257   * Removes all filters modifying the rel attribute of targeted links.
3258   *
3259   * @since 5.1.0
3260   */
3261  function wp_remove_targeted_link_rel_filters() {
3262      $filters = array(
3263          'title_save_pre',
3264          'content_save_pre',
3265          'excerpt_save_pre',
3266          'content_filtered_save_pre',
3267          'pre_comment_content',
3268          'pre_term_description',
3269          'pre_link_description',
3270          'pre_link_notes',
3271          'pre_user_description',
3272      );
3273  
3274      foreach ( $filters as $filter ) {
3275          remove_filter( $filter, 'wp_targeted_link_rel' );
3276      };
3277  }
3278  
3279  /**
3280   * Convert one smiley code to the icon graphic file equivalent.
3281   *
3282   * Callback handler for convert_smilies().
3283   *
3284   * Looks up one smiley code in the $wpsmiliestrans global array and returns an
3285   * `<img>` string for that smiley.
3286   *
3287   * @since 2.8.0
3288   *
3289   * @global array $wpsmiliestrans
3290   *
3291   * @param array $matches Single match. Smiley code to convert to image.
3292   * @return string Image string for smiley.
3293   */
3294  function translate_smiley( $matches ) {
3295      global $wpsmiliestrans;
3296  
3297      if ( count( $matches ) == 0 ) {
3298          return '';
3299      }
3300  
3301      $smiley = trim( reset( $matches ) );
3302      $img    = $wpsmiliestrans[ $smiley ];
3303  
3304      $matches    = array();
3305      $ext        = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
3306      $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
3307  
3308      // Don't convert smilies that aren't images - they're probably emoji.
3309      if ( ! in_array( $ext, $image_exts, true ) ) {
3310          return $img;
3311      }
3312  
3313      /**
3314       * Filters the Smiley image URL before it's used in the image element.
3315       *
3316       * @since 2.9.0
3317       *
3318       * @param string $smiley_url URL for the smiley image.
3319       * @param string $img        Filename for the smiley image.
3320       * @param string $site_url   Site URL, as returned by site_url().
3321       */
3322      $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
3323  
3324      return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
3325  }
3326  
3327  /**
3328   * Convert text equivalent of smilies to images.
3329   *
3330   * Will only convert smilies if the option 'use_smilies' is true and the global
3331   * used in the function isn't empty.
3332   *
3333   * @since 0.71
3334   *
3335   * @global string|array $wp_smiliessearch
3336   *
3337   * @param string $text Content to convert smilies from text.
3338   * @return string Converted content with text smilies replaced with images.
3339   */
3340  function convert_smilies( $text ) {
3341      global $wp_smiliessearch;
3342      $output = '';
3343      if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
3344          // HTML loop taken from texturize function, could possible be consolidated.
3345          $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // Capture the tags as well as in between.
3346          $stop    = count( $textarr ); // Loop stuff.
3347  
3348          // Ignore proessing of specific tags.
3349          $tags_to_ignore       = 'code|pre|style|script|textarea';
3350          $ignore_block_element = '';
3351  
3352          for ( $i = 0; $i < $stop; $i++ ) {
3353              $content = $textarr[ $i ];
3354  
3355              // If we're in an ignore block, wait until we find its closing tag.
3356              if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')[^>]*>/', $content, $matches ) ) {
3357                  $ignore_block_element = $matches[1];
3358              }
3359  
3360              // If it's not a tag and not in ignore block.
3361              if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
3362                  $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
3363              }
3364  
3365              // Did we exit ignore block?
3366              if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
3367                  $ignore_block_element = '';
3368              }
3369  
3370              $output .= $content;
3371          }
3372      } else {
3373          // Return default text.
3374          $output = $text;
3375      }
3376      return $output;
3377  }
3378  
3379  /**
3380   * Verifies that an email is valid.
3381   *
3382   * Does not grok i18n domains. Not RFC compliant.
3383   *
3384   * @since 0.71
3385   *
3386   * @param string $email      Email address to verify.
3387   * @param bool   $deprecated Deprecated.
3388   * @return string|false Valid email address on success, false on failure.
3389   */
3390  function is_email( $email, $deprecated = false ) {
3391      if ( ! empty( $deprecated ) ) {
3392          _deprecated_argument( __FUNCTION__, '3.0.0' );
3393      }
3394  
3395      // Test for the minimum length the email can be.
3396      if ( strlen( $email ) < 6 ) {
3397          /**
3398           * Filters whether an email address is valid.
3399           *
3400           * This filter is evaluated under several different contexts, such as 'email_too_short',
3401           * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
3402           * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
3403           *
3404           * @since 2.8.0
3405           *
3406           * @param string|false $is_email The email address if successfully passed the is_email() checks, false otherwise.
3407           * @param string       $email    The email address being checked.
3408           * @param string       $context  Context under which the email was tested.
3409           */
3410          return apply_filters( 'is_email', false, $email, 'email_too_short' );
3411      }
3412  
3413      // Test for an @ character after the first position.
3414      if ( strpos( $email, '@', 1 ) === false ) {
3415          /** This filter is documented in wp-includes/formatting.php */
3416          return apply_filters( 'is_email', false, $email, 'email_no_at' );
3417      }
3418  
3419      // Split out the local and domain parts.
3420      list( $local, $domain ) = explode( '@', $email, 2 );
3421  
3422      // LOCAL PART
3423      // Test for invalid characters.
3424      if ( ! preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
3425          /** This filter is documented in wp-includes/formatting.php */
3426          return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
3427      }
3428  
3429      // DOMAIN PART
3430      // Test for sequences of periods.
3431      if ( preg_match( '/\.{2,}/', $domain ) ) {
3432          /** This filter is documented in wp-includes/formatting.php */
3433          return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
3434      }
3435  
3436      // Test for leading and trailing periods and whitespace.
3437      if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
3438          /** This filter is documented in wp-includes/formatting.php */
3439          return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
3440      }
3441  
3442      // Split the domain into subs.
3443      $subs = explode( '.', $domain );
3444  
3445      // Assume the domain will have at least two subs.
3446      if ( 2 > count( $subs ) ) {
3447          /** This filter is documented in wp-includes/formatting.php */
3448          return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
3449      }
3450  
3451      // Loop through each sub.
3452      foreach ( $subs as $sub ) {
3453          // Test for leading and trailing hyphens and whitespace.
3454          if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
3455              /** This filter is documented in wp-includes/formatting.php */
3456              return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
3457          }
3458  
3459          // Test for invalid characters.
3460          if ( ! preg_match( '/^[a-z0-9-]+$/i', $sub ) ) {
3461              /** This filter is documented in wp-includes/formatting.php */
3462              return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
3463          }
3464      }
3465  
3466      // Congratulations, your email made it!
3467      /** This filter is documented in wp-includes/formatting.php */
3468      return apply_filters( 'is_email', $email, $email, null );
3469  }
3470  
3471  /**
3472   * Convert to ASCII from email subjects.
3473   *
3474   * @since 1.2.0
3475   *
3476   * @param string $string Subject line
3477   * @return string Converted string to ASCII
3478   */
3479  function wp_iso_descrambler( $string ) {
3480      /* this may only work with iso-8859-1, I'm afraid */
3481      if ( ! preg_match( '#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches ) ) {
3482          return $string;
3483      } else {
3484          $subject = str_replace( '_', ' ', $matches[2] );
3485          return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
3486      }
3487  }
3488  
3489  /**
3490   * Helper function to convert hex encoded chars to ASCII
3491   *
3492   * @since 3.1.0
3493   * @access private
3494   *
3495   * @param array $match The preg_replace_callback matches array
3496   * @return string Converted chars
3497   */
3498  function _wp_iso_convert( $match ) {
3499      return chr( hexdec( strtolower( $match[1] ) ) );
3500  }
3501  
3502  /**
3503   * Given a date in the timezone of the site, returns that date in UTC.
3504   *
3505   * Requires and returns a date in the Y-m-d H:i:s format.
3506   * Return format can be overridden using the $format parameter.
3507   *
3508   * @since 1.2.0
3509   *
3510   * @param string $string The date to be converted, in the timezone of the site.
3511   * @param string $format The format string for the returned date. Default 'Y-m-d H:i:s'.
3512   * @return string Formatted version of the date, in UTC.
3513   */
3514  function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
3515      $datetime = date_create( $string, wp_timezone() );
3516  
3517      if ( false === $datetime ) {
3518          return gmdate( $format, 0 );
3519      }
3520  
3521      return $datetime->setTimezone( new DateTimeZone( 'UTC' ) )->format( $format );
3522  }
3523  
3524  /**
3525   * Given a date in UTC or GMT timezone, returns that date in the timezone of the site.
3526   *
3527   * Requires and returns a date in the Y-m-d H:i:s format.
3528   * Return format can be overridden using the $format parameter.
3529   *
3530   * @since 1.2.0
3531   *
3532   * @param string $string The date to be converted, in UTC or GMT timezone.
3533   * @param string $format The format string for the returned date. Default 'Y-m-d H:i:s'.
3534   * @return string Formatted version of the date, in the site's timezone.
3535   */
3536  function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
3537      $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
3538  
3539      if ( false === $datetime ) {
3540          return gmdate( $format, 0 );
3541      }
3542  
3543      return $datetime->setTimezone( wp_timezone() )->format( $format );
3544  }
3545  
3546  /**
3547   * Given an ISO 8601 timezone, returns its UTC offset in seconds.
3548   *
3549   * @since 1.5.0
3550   *
3551   * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
3552   * @return int|float The offset in seconds.
3553   */
3554  function iso8601_timezone_to_offset( $timezone ) {
3555      // $timezone is either 'Z' or '[+|-]hhmm'.
3556      if ( 'Z' === $timezone ) {
3557          $offset = 0;
3558      } else {
3559          $sign    = ( substr( $timezone, 0, 1 ) == '+' ) ? 1 : -1;
3560          $hours   = intval( substr( $timezone, 1, 2 ) );
3561          $minutes = intval( substr( $timezone, 3, 4 ) ) / 60;
3562          $offset  = $sign * HOUR_IN_SECONDS * ( $hours + $minutes );
3563      }
3564      return $offset;
3565  }
3566  
3567  /**
3568   * Given an ISO 8601 (Ymd\TH:i:sO) date, returns a MySQL DateTime (Y-m-d H:i:s) format used by post_date[_gmt].
3569   *
3570   * @since 1.5.0
3571   *
3572   * @param string $date_string Date and time in ISO 8601 format {@link https://en.wikipedia.org/wiki/ISO_8601}.
3573   * @param string $timezone    Optional. If set to 'gmt' returns the result in UTC. Default 'user'.
3574   * @return string|bool The date and time in MySQL DateTime format - Y-m-d H:i:s, or false on failure.
3575   */
3576  function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
3577      $timezone    = strtolower( $timezone );
3578      $wp_timezone = wp_timezone();
3579      $datetime    = date_create( $date_string, $wp_timezone ); // Timezone is ignored if input has one.
3580  
3581      if ( false === $datetime ) {
3582          return false;
3583      }
3584  
3585      if ( 'gmt' === $timezone ) {
3586          return $datetime->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s' );
3587      }
3588  
3589      if ( 'user' === $timezone ) {
3590          return $datetime->setTimezone( $wp_timezone )->format( 'Y-m-d H:i:s' );
3591      }
3592  
3593      return false;
3594  }
3595  
3596  /**
3597   * Strips out all characters that are not allowable in an email.
3598   *
3599   * @since 1.5.0
3600   *
3601   * @param string $email Email address to filter.
3602   * @return string Filtered email address.
3603   */
3604  function sanitize_email( $email ) {
3605      // Test for the minimum length the email can be.
3606      if ( strlen( $email ) < 6 ) {
3607          /**
3608           * Filters a sanitized email address.
3609           *
3610           * This filter is evaluated under several contexts, including 'email_too_short',
3611           * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
3612           * 'domain_no_periods', 'domain_no_valid_subs', or no context.
3613           *
3614           * @since 2.8.0
3615           *
3616           * @param string $sanitized_email The sanitized email address.
3617           * @param string $email           The email address, as provided to sanitize_email().
3618           * @param string|null $message    A message to pass to the user. null if email is sanitized.
3619           */
3620          return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
3621      }
3622  
3623      // Test for an @ character after the first position.
3624      if ( strpos( $email, '@', 1 ) === false ) {
3625          /** This filter is documented in wp-includes/formatting.php */
3626          return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
3627      }
3628  
3629      // Split out the local and domain parts.
3630      list( $local, $domain ) = explode( '@', $email, 2 );
3631  
3632      // LOCAL PART
3633      // Test for invalid characters.
3634      $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
3635      if ( '' === $local ) {
3636          /** This filter is documented in wp-includes/formatting.php */
3637          return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
3638      }
3639  
3640      // DOMAIN PART
3641      // Test for sequences of periods.
3642      $domain = preg_replace( '/\.{2,}/', '', $domain );
3643      if ( '' === $domain ) {
3644          /** This filter is documented in wp-includes/formatting.php */
3645          return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
3646      }
3647  
3648      // Test for leading and trailing periods and whitespace.
3649      $domain = trim( $domain, " \t\n\r\0\x0B." );
3650      if ( '' === $domain ) {
3651          /** This filter is documented in wp-includes/formatting.php */
3652          return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
3653      }
3654  
3655      // Split the domain into subs.
3656      $subs = explode( '.', $domain );
3657  
3658      // Assume the domain will have at least two subs.
3659      if ( 2 > count( $subs ) ) {
3660          /** This filter is documented in wp-includes/formatting.php */
3661          return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
3662      }
3663  
3664      // Create an array that will contain valid subs.
3665      $new_subs = array();
3666  
3667      // Loop through each sub.
3668      foreach ( $subs as $sub ) {
3669          // Test for leading and trailing hyphens.
3670          $sub = trim( $sub, " \t\n\r\0\x0B-" );
3671  
3672          // Test for invalid characters.
3673          $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
3674  
3675          // If there's anything left, add it to the valid subs.
3676          if ( '' !== $sub ) {
3677              $new_subs[] = $sub;
3678          }
3679      }
3680  
3681      // If there aren't 2 or more valid subs.
3682      if ( 2 > count( $new_subs ) ) {
3683          /** This filter is documented in wp-includes/formatting.php */
3684          return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
3685      }
3686  
3687      // Join valid subs into the new domain.
3688      $domain = join( '.', $new_subs );
3689  
3690      // Put the email back together.
3691      $sanitized_email = $local . '@' . $domain;
3692  
3693      // Congratulations, your email made it!
3694      /** This filter is documented in wp-includes/formatting.php */
3695      return apply_filters( 'sanitize_email', $sanitized_email, $email, null );
3696  }
3697  
3698  /**
3699   * Determines the difference between two timestamps.
3700   *
3701   * The difference is returned in a human readable format such as "1 hour",
3702   * "5 mins", "2 days".
3703   *
3704   * @since 1.5.0
3705   * @since 5.3.0 Added support for showing a difference in seconds.
3706   *
3707   * @param int $from Unix timestamp from which the difference begins.
3708   * @param int $to   Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
3709   * @return string Human readable time difference.
3710   */
3711  function human_time_diff( $from, $to = 0 ) {
3712      if ( empty( $to ) ) {
3713          $to = time();
3714      }
3715  
3716      $diff = (int) abs( $to - $from );
3717  
3718      if ( $diff < MINUTE_IN_SECONDS ) {
3719          $secs = $diff;
3720          if ( $secs <= 1 ) {
3721              $secs = 1;
3722          }
3723          /* translators: Time difference between two dates, in seconds. %s: Number of seconds. */
3724          $since = sprintf( _n( '%s second', '%s seconds', $secs ), $secs );
3725      } elseif ( $diff < HOUR_IN_SECONDS && $diff >= MINUTE_IN_SECONDS ) {
3726          $mins = round( $diff / MINUTE_IN_SECONDS );
3727          if ( $mins <= 1 ) {
3728              $mins = 1;
3729          }
3730          /* translators: Time difference between two dates, in minutes (min=minute). %s: Number of minutes. */
3731          $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
3732      } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
3733          $hours = round( $diff / HOUR_IN_SECONDS );
3734          if ( $hours <= 1 ) {
3735              $hours = 1;
3736          }
3737          /* translators: Time difference between two dates, in hours. %s: Number of hours. */
3738          $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
3739      } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
3740          $days = round( $diff / DAY_IN_SECONDS );
3741          if ( $days <= 1 ) {
3742              $days = 1;
3743          }
3744          /* translators: Time difference between two dates, in days. %s: Number of days. */
3745          $since = sprintf( _n( '%s day', '%s days', $days ), $days );
3746      } elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
3747          $weeks = round( $diff / WEEK_IN_SECONDS );
3748          if ( $weeks <= 1 ) {
3749              $weeks = 1;
3750          }
3751          /* translators: Time difference between two dates, in weeks. %s: Number of weeks. */
3752          $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
3753      } elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
3754          $months = round( $diff / MONTH_IN_SECONDS );
3755          if ( $months <= 1 ) {
3756              $months = 1;
3757          }
3758          /* translators: Time difference between two dates, in months. %s: Number of months. */
3759          $since = sprintf( _n( '%s month', '%s months', $months ), $months );
3760      } elseif ( $diff >= YEAR_IN_SECONDS ) {
3761          $years = round( $diff / YEAR_IN_SECONDS );
3762          if ( $years <= 1 ) {
3763              $years = 1;
3764          }
3765          /* translators: Time difference between two dates, in years. %s: Number of years. */
3766          $since = sprintf( _n( '%s year', '%s years', $years ), $years );
3767      }
3768  
3769      /**
3770       * Filters the human readable difference between two timestamps.
3771       *
3772       * @since 4.0.0
3773       *
3774       * @param string $since The difference in human readable text.
3775       * @param int    $diff  The difference in seconds.
3776       * @param int    $from  Unix timestamp from which the difference begins.
3777       * @param int    $to    Unix timestamp to end the time difference.
3778       */
3779      return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
3780  }
3781  
3782  /**
3783   * Generates an excerpt from the content, if needed.
3784   *
3785   * Returns a maximum of 55 words with an ellipsis appended if necessary.
3786   *
3787   * The 55 word limit can be modified by plugins/themes using the {@see 'excerpt_length'} filter
3788   * The ' [&hellip;]' string can be modified by plugins/themes using the {@see 'excerpt_more'} filter
3789   *
3790   * @since 1.5.0
3791   * @since 5.2.0 Added the `$post` parameter.
3792   *
3793   * @param string             $text Optional. The excerpt. If set to empty, an excerpt is generated.
3794   * @param WP_Post|object|int $post Optional. WP_Post instance or Post ID/object. Default is null.
3795   * @return string The excerpt.
3796   */
3797  function wp_trim_excerpt( $text = '', $post = null ) {
3798      $raw_excerpt = $text;
3799      if ( '' == $text ) {
3800          $post = get_post( $post );
3801          $text = get_the_content( '', false, $post );
3802  
3803          $text = strip_shortcodes( $text );
3804          $text = excerpt_remove_blocks( $text );
3805  
3806          /** This filter is documented in wp-includes/post-template.php */
3807          $text = apply_filters( 'the_content', $text );
3808          $text = str_replace( ']]>', ']]&gt;', $text );
3809  
3810          /* translators: Maximum number of words used in a post excerpt. */
3811          $excerpt_length = intval( _x( '55', 'excerpt_length' ) );
3812  
3813          /**
3814           * Filters the maximum number of words in a post excerpt.
3815           *
3816           * @since 2.7.0
3817           *
3818           * @param int $number The maximum number of words. Default 55.
3819           */
3820          $excerpt_length = (int) apply_filters( 'excerpt_length', $excerpt_length );
3821  
3822          /**
3823           * Filters the string in the "more" link displayed after a trimmed excerpt.
3824           *
3825           * @since 2.9.0
3826           *
3827           * @param string $more_string The string shown within the more link.
3828           */
3829          $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
3830          $text         = wp_trim_words( $text, $excerpt_length, $excerpt_more );
3831      }
3832  
3833      /**
3834       * Filters the trimmed excerpt string.
3835       *
3836       * @since 2.8.0
3837       *
3838       * @param string $text        The trimmed text.
3839       * @param string $raw_excerpt The text prior to trimming.
3840       */
3841      return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
3842  }
3843  
3844  /**
3845   * Trims text to a certain number of words.
3846   *
3847   * This function is localized. For languages that count 'words' by the individual
3848   * character (such as East Asian languages), the $num_words argument will apply
3849   * to the number of individual characters.
3850   *
3851   * @since 3.3.0
3852   *
3853   * @param string $text      Text to trim.
3854   * @param int    $num_words Number of words. Default 55.
3855   * @param string $more      Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
3856   * @return string Trimmed text.
3857   */
3858  function wp_trim_words( $text, $num_words = 55, $more = null ) {
3859      if ( null === $more ) {
3860          $more = __( '&hellip;' );
3861      }
3862  
3863      $original_text = $text;
3864      $text          = wp_strip_all_tags( $text );
3865      $num_words     = (int) $num_words;
3866  
3867      /*
3868       * translators: If your word count is based on single characters (e.g. East Asian characters),
3869       * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
3870       * Do not translate into your own language.
3871       */
3872      if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
3873          $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
3874          preg_match_all( '/./u', $text, $words_array );
3875          $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
3876          $sep         = '';
3877      } else {
3878          $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
3879          $sep         = ' ';
3880      }
3881  
3882      if ( count( $words_array ) > $num_words ) {
3883          array_pop( $words_array );
3884          $text = implode( $sep, $words_array );
3885          $text = $text . $more;
3886      } else {
3887          $text = implode( $sep, $words_array );
3888      }
3889  
3890      /**
3891       * Filters the text content after words have been trimmed.
3892       *
3893       * @since 3.3.0
3894       *
3895       * @param string $text          The trimmed text.
3896       * @param int    $num_words     The number of words to trim the text to. Default 55.
3897       * @param string $more          An optional string to append to the end of the trimmed text, e.g. &hellip;.
3898       * @param string $original_text The text before it was trimmed.
3899       */
3900      return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
3901  }
3902  
3903  /**
3904   * Converts named entities into numbered entities.
3905   *
3906   * @since 1.5.1
3907   *
3908   * @param string $text The text within which entities will be converted.
3909   * @return string Text with converted entities.
3910   */
3911  function ent2ncr( $text ) {
3912  
3913      /**
3914       * Filters text before named entities are converted into numbered entities.
3915       *
3916       * A non-null string must be returned for the filter to be evaluated.
3917       *
3918       * @since 3.3.0
3919       *
3920       * @param string|null $converted_text The text to be converted. Default null.
3921       * @param string      $text           The text prior to entity conversion.
3922       */
3923      $filtered = apply_filters( 'pre_ent2ncr', null, $text );
3924      if ( null !== $filtered ) {
3925          return $filtered;
3926      }
3927  
3928      $to_ncr = array(
3929          '&quot;'     => '&#34;',
3930          '&amp;'      => '&#38;',
3931          '&lt;'       => '&#60;',
3932          '&gt;'       => '&#62;',
3933          '|'          => '&#124;',
3934          '&nbsp;'     => '&#160;',
3935          '&iexcl;'    => '&#161;',
3936          '&cent;'     => '&#162;',
3937          '&pound;'    => '&#163;',
3938          '&curren;'   => '&#164;',
3939          '&yen;'      => '&#165;',
3940          '&brvbar;'   => '&#166;',
3941          '&brkbar;'   => '&#166;',
3942          '&sect;'     => '&#167;',
3943          '&uml;'      => '&#168;',
3944          '&die;'      => '&#168;',
3945          '&copy;'     => '&#169;',
3946          '&ordf;'     => '&#170;',
3947          '&laquo;'    => '&#171;',
3948          '&not;'      => '&#172;',
3949          '&shy;'      => '&#173;',
3950          '&reg;'      => '&#174;',
3951          '&macr;'     => '&#175;',
3952          '&hibar;'    => '&#175;',
3953          '&deg;'      => '&#176;',
3954          '&plusmn;'   => '&#177;',
3955          '&sup2;'     => '&#178;',
3956          '&sup3;'     => '&#179;',
3957          '&acute;'    => '&#180;',
3958          '&micro;'    => '&#181;',
3959          '&para;'     => '&#182;',
3960          '&middot;'   => '&#183;',
3961          '&cedil;'    => '&#184;',
3962          '&sup1;'     => '&#185;',
3963          '&ordm;'     => '&#186;',
3964          '&raquo;'    => '&#187;',
3965          '&frac14;'   => '&#188;',
3966          '&frac12;'   => '&#189;',
3967          '&frac34;'   => '&#190;',
3968          '&iquest;'   => '&#191;',
3969          '&Agrave;'   => '&#192;',
3970          '&Aacute;'   => '&#193;',
3971          '&Acirc;'    => '&#194;',
3972          '&Atilde;'   => '&#195;',
3973          '&Auml;'     => '&#196;',
3974          '&Aring;'    => '&#197;',
3975          '&AElig;'    => '&#198;',
3976          '&Ccedil;'   => '&#199;',
3977          '&Egrave;'   => '&#200;',
3978          '&Eacute;'   => '&#201;',
3979          '&Ecirc;'    => '&#202;',
3980          '&Euml;'     => '&#203;',
3981          '&Igrave;'   => '&#204;',
3982          '&Iacute;'   => '&#205;',
3983          '&Icirc;'    => '&#206;',
3984          '&Iuml;'     => '&#207;',
3985          '&ETH;'      => '&#208;',
3986          '&Ntilde;'   => '&#209;',
3987          '&Ograve;'   => '&#210;',
3988          '&Oacute;'   => '&#211;',
3989          '&Ocirc;'    => '&#212;',
3990          '&Otilde;'   => '&#213;',
3991          '&Ouml;'     => '&#214;',
3992          '&times;'    => '&#215;',
3993          '&Oslash;'   => '&#216;',
3994          '&Ugrave;'   => '&#217;',
3995          '&Uacute;'   => '&#218;',
3996          '&Ucirc;'    => '&#219;',
3997          '&Uuml;'     => '&#220;',
3998          '&Yacute;'   => '&#221;',
3999          '&THORN;'    => '&#222;',
4000          '&szlig;'    => '&#223;',
4001          '&agrave;'   => '&#224;',
4002          '&aacute;'   => '&#225;',
4003          '&acirc;'    => '&#226;',
4004          '&atilde;'   => '&#227;',
4005          '&auml;'     => '&#228;',
4006          '&aring;'    => '&#229;',
4007          '&aelig;'    => '&#230;',
4008          '&ccedil;'   => '&#231;',
4009          '&egrave;'   => '&#232;',
4010          '&eacute;'   => '&#233;',
4011          '&ecirc;'    => '&#234;',
4012          '&euml;'     => '&#235;',
4013          '&igrave;'   => '&#236;',
4014          '&iacute;'   => '&#237;',
4015          '&icirc;'    => '&#238;',
4016          '&iuml;'     => '&#239;',
4017          '&eth;'      => '&#240;',
4018          '&ntilde;'   => '&#241;',
4019          '&ograve;'   => '&#242;',
4020          '&oacute;'   => '&#243;',
4021          '&ocirc;'    => '&#244;',
4022          '&otilde;'   => '&#245;',
4023          '&ouml;'     => '&#246;',
4024          '&divide;'   => '&#247;',
4025          '&oslash;'   => '&#248;',
4026          '&ugrave;'   => '&#249;',
4027          '&uacute;'   => '&#250;',
4028          '&ucirc;'    => '&#251;',
4029          '&uuml;'     => '&#252;',
4030          '&yacute;'   => '&#253;',
4031          '&thorn;'    => '&#254;',
4032          '&yuml;'     => '&#255;',
4033          '&OElig;'    => '&#338;',
4034          '&oelig;'    => '&#339;',
4035          '&Scaron;'   => '&#352;',
4036          '&scaron;'   => '&#353;',
4037          '&Yuml;'     => '&#376;',
4038          '&fnof;'     => '&#402;',
4039          '&circ;'     => '&#710;',
4040          '&tilde;'    => '&#732;',
4041          '&Alpha;'    => '&#913;',
4042          '&Beta;'     => '&#914;',
4043          '&Gamma;'    => '&#915;',
4044          '&Delta;'    => '&#916;',
4045          '&Epsilon;'  => '&#917;',
4046          '&Zeta;'     => '&#918;',
4047          '&Eta;'      => '&#919;',
4048          '&Theta;'    => '&#920;',
4049          '&Iota;'     => '&#921;',
4050          '&Kappa;'    => '&#922;',
4051          '&Lambda;'   => '&#923;',
4052          '&Mu;'       => '&#924;',
4053          '&Nu;'       => '&#925;',
4054          '&Xi;'       => '&#926;',
4055          '&Omicron;'  => '&#927;',
4056          '&Pi;'       => '&#928;',
4057          '&Rho;'      => '&#929;',
4058          '&Sigma;'    => '&#931;',
4059          '&Tau;'      => '&#932;',
4060          '&Upsilon;'  => '&#933;',
4061          '&Phi;'      => '&#934;',
4062          '&Chi;'      => '&#935;',
4063          '&Psi;'      => '&#936;',
4064          '&Omega;'    => '&#937;',
4065          '&alpha;'    => '&#945;',
4066          '&beta;'     => '&#946;',
4067          '&gamma;'    => '&#947;',
4068          '&delta;'    => '&#948;',
4069          '&epsilon;'  => '&#949;',
4070          '&zeta;'     => '&#950;',
4071          '&eta;'      => '&#951;',
4072          '&theta;'    => '&#952;',
4073          '&iota;'     => '&#953;',
4074          '&kappa;'    => '&#954;',
4075          '&lambda;'   => '&#955;',
4076          '&mu;'       => '&#956;',
4077          '&nu;'       => '&#957;',
4078          '&xi;'       => '&#958;',
4079          '&omicron;'  => '&#959;',
4080          '&pi;'       => '&#960;',
4081          '&rho;'      => '&#961;',
4082          '&sigmaf;'   => '&#962;',
4083          '&sigma;'    => '&#963;',
4084          '&tau;'      => '&#964;',
4085          '&upsilon;'  => '&#965;',
4086          '&phi;'      => '&#966;',
4087          '&chi;'      => '&#967;',
4088          '&psi;'      => '&#968;',
4089          '&omega;'    => '&#969;',
4090          '&thetasym;' => '&#977;',
4091          '&upsih;'    => '&#978;',
4092          '&piv;'      => '&#982;',
4093          '&ensp;'     => '&#8194;',
4094          '&emsp;'     => '&#8195;',
4095          '&thinsp;'   => '&#8201;',
4096          '&zwnj;'     => '&#8204;',
4097          '&zwj;'      => '&#8205;',
4098          '&lrm;'      => '&#8206;',
4099          '&rlm;'      => '&#8207;',
4100          '&ndash;'    => '&#8211;',
4101          '&mdash;'    => '&#8212;',
4102          '&lsquo;'    => '&#8216;',
4103          '&rsquo;'    => '&#8217;',
4104          '&sbquo;'    => '&#8218;',
4105          '&ldquo;'    => '&#8220;',
4106          '&rdquo;'    => '&#8221;',
4107          '&bdquo;'    => '&#8222;',
4108          '&dagger;'   => '&#8224;',
4109          '&Dagger;'   => '&#8225;',
4110          '&bull;'     => '&#8226;',
4111          '&hellip;'   => '&#8230;',
4112          '&permil;'   => '&#8240;',
4113          '&prime;'    => '&#8242;',
4114          '&Prime;'    => '&#8243;',
4115          '&lsaquo;'   => '&#8249;',
4116          '&rsaquo;'   => '&#8250;',
4117          '&oline;'    => '&#8254;',
4118          '&frasl;'    => '&#8260;',
4119          '&euro;'     => '&#8364;',
4120          '&image;'    => '&#8465;',
4121          '&weierp;'   => '&#8472;',
4122          '&real;'     => '&#8476;',
4123          '&trade;'    => '&#8482;',
4124          '&alefsym;'  => '&#8501;',
4125          '&crarr;'    => '&#8629;',
4126          '&lArr;'     => '&#8656;',
4127          '&uArr;'     => '&#8657;',
4128          '&rArr;'     => '&#8658;',
4129          '&dArr;'     => '&#8659;',
4130          '&hArr;'     => '&#8660;',
4131          '&forall;'   => '&#8704;',
4132          '&part;'     => '&#8706;',
4133          '&exist;'    => '&#8707;',
4134          '&empty;'    => '&#8709;',
4135          '&nabla;'    => '&#8711;',
4136          '&isin;'     => '&#8712;',
4137          '&notin;'    => '&#8713;',
4138          '&ni;'       => '&#8715;',
4139          '&prod;'     => '&#8719;',
4140          '&sum;'      => '&#8721;',
4141          '&minus;'    => '&#8722;',
4142          '&lowast;'   => '&#8727;',
4143          '&radic;'    => '&#8730;',
4144          '&prop;'     => '&#8733;',
4145          '&infin;'    => '&#8734;',
4146          '&ang;'      => '&#8736;',
4147          '&and;'      => '&#8743;',
4148          '&or;'       => '&#8744;',
4149          '&cap;'      => '&#8745;',
4150          '&cup;'      => '&#8746;',
4151          '&int;'      => '&#8747;',
4152          '&there4;'   => '&#8756;',
4153          '&sim;'      => '&#8764;',
4154          '&cong;'     => '&#8773;',
4155          '&asymp;'    => '&#8776;',
4156          '&ne;'       => '&#8800;',
4157          '&equiv;'    => '&#8801;',
4158          '&le;'       => '&#8804;',
4159          '&ge;'       => '&#8805;',
4160          '&sub;'      => '&#8834;',
4161          '&sup;'      => '&#8835;',
4162          '&nsub;'     => '&#8836;',
4163          '&sube;'     => '&#8838;',
4164          '&supe;'     => '&#8839;',
4165          '&oplus;'    => '&#8853;',
4166          '&otimes;'   => '&#8855;',
4167          '&perp;'     => '&#8869;',
4168          '&sdot;'     => '&#8901;',
4169          '&lceil;'    => '&#8968;',
4170          '&rceil;'    => '&#8969;',
4171          '&lfloor;'   => '&#8970;',
4172          '&rfloor;'   => '&#8971;',
4173          '&lang;'     => '&#9001;',
4174          '&rang;'     => '&#9002;',
4175          '&larr;'     => '&#8592;',
4176          '&uarr;'     => '&#8593;',
4177          '&rarr;'     => '&#8594;',
4178          '&darr;'     => '&#8595;',
4179          '&harr;'     => '&#8596;',
4180          '&loz;'      => '&#9674;',
4181          '&spades;'   => '&#9824;',
4182          '&clubs;'    => '&#9827;',
4183          '&hearts;'   => '&#9829;',
4184          '&diams;'    => '&#9830;',
4185      );
4186  
4187      return str_replace( array_keys( $to_ncr ), array_values( $to_ncr ), $text );
4188  }
4189  
4190  /**
4191   * Formats text for the editor.
4192   *
4193   * Generally the browsers treat everything inside a textarea as text, but
4194   * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
4195   *
4196   * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
4197   * filter will be applied to an empty string.
4198   *
4199   * @since 4.3.0
4200   *
4201   * @see _WP_Editors::editor()
4202   *
4203   * @param string $text           The text to be formatted.
4204   * @param string $default_editor The default editor for the current user.
4205   *                               It is usually either 'html' or 'tinymce'.
4206   * @return string The formatted text after filter is applied.
4207   */
4208  function format_for_editor( $text, $default_editor = null ) {
4209      if ( $text ) {
4210          $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
4211      }
4212  
4213      /**
4214       * Filters the text after it is formatted for the editor.
4215       *
4216       * @since 4.3.0
4217       *
4218       * @param string $text           The formatted text.
4219       * @param string $default_editor The default editor for the current user.
4220       *                               It is usually either 'html' or 'tinymce'.
4221       */
4222      return apply_filters( 'format_for_editor', $text, $default_editor );
4223  }
4224  
4225  /**
4226   * Perform a deep string replace operation to ensure the values in $search are no longer present
4227   *
4228   * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
4229   * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
4230   * str_replace would return
4231   *
4232   * @since 2.8.1
4233   * @access private
4234   *
4235   * @param string|array $search  The value being searched for, otherwise known as the needle.
4236   *                              An array may be used to designate multiple needles.
4237   * @param string       $subject The string being searched and replaced on, otherwise known as the haystack.
4238   * @return string The string with the replaced values.
4239   */
4240  function _deep_replace( $search, $subject ) {
4241      $subject = (string) $subject;
4242  
4243      $count = 1;
4244      while ( $count ) {
4245          $subject = str_replace( $search, '', $subject, $count );
4246      }
4247  
4248      return $subject;
4249  }
4250  
4251  /**
4252   * Escapes data for use in a MySQL query.
4253   *
4254   * Usually you should prepare queries using wpdb::prepare().
4255   * Sometimes, spot-escaping is required or useful. One example
4256   * is preparing an array for use in an IN clause.
4257   *
4258   * NOTE: Since 4.8.3, '%' characters will be replaced with a placeholder string,
4259   * this prevents certain SQLi attacks from taking place. This change in behaviour
4260   * may cause issues for code that expects the return value of esc_sql() to be useable
4261   * for other purposes.
4262   *
4263   * @since 2.8.0
4264   *
4265   * @global wpdb $wpdb WordPress database abstraction object.
4266   *
4267   * @param string|array $data Unescaped data
4268   * @return string|array Escaped data
4269   */
4270  function esc_sql( $data ) {
4271      global $wpdb;
4272      return $wpdb->_escape( $data );
4273  }
4274  
4275  /**
4276   * Checks and cleans a URL.
4277   *
4278   * A number of characters are removed from the URL. If the URL is for displaying
4279   * (the default behaviour) ampersands are also replaced. The {@see 'clean_url'} filter
4280   * is applied to the returned cleaned URL.
4281   *
4282   * @since 2.8.0
4283   *
4284   * @param string   $url       The URL to be cleaned.
4285   * @param string[] $protocols Optional. An array of acceptable protocols.
4286   *                            Defaults to return value of wp_allowed_protocols()
4287   * @param string   $_context  Private. Use esc_url_raw() for database usage.
4288   * @return string The cleaned $url after the {@see 'clean_url'} filter is applied.
4289   */
4290  function esc_url( $url, $protocols = null, $_context = 'display' ) {
4291      $original_url = $url;
4292  
4293      if ( '' == $url ) {
4294          return $url;
4295      }
4296  
4297      $url = str_replace( ' ', '%20', ltrim( $url ) );
4298      $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );
4299  
4300      if ( '' === $url ) {
4301          return $url;
4302      }
4303  
4304      if ( 0 !== stripos( $url, 'mailto:' ) ) {
4305          $strip = array( '%0d', '%0a', '%0D', '%0A' );
4306          $url   = _deep_replace( $strip, $url );
4307      }
4308  
4309      $url = str_replace( ';//', '://', $url );
4310      /*
4311       * If the URL doesn't appear to contain a scheme, we presume
4312       * it needs http:// prepended (unless it's a relative link
4313       * starting with /, # or ?, or a PHP file).
4314       */
4315      if ( strpos( $url, ':' ) === false && ! in_array( $url[0], array( '/', '#', '?' ), true ) &&
4316          ! preg_match( '/^[a-z0-9-]+?\.php/i', $url ) ) {
4317          $url = 'http://' . $url;
4318      }
4319  
4320      // Replace ampersands and single quotes only when displaying.
4321      if ( 'display' == $_context ) {
4322          $url = wp_kses_normalize_entities( $url );
4323          $url = str_replace( '&amp;', '&#038;', $url );
4324          $url = str_replace( "'", '&#039;', $url );
4325      }
4326  
4327      if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
4328  
4329          $parsed = wp_parse_url( $url );
4330          $front  = '';
4331  
4332          if ( isset( $parsed['scheme'] ) ) {
4333              $front .= $parsed['scheme'] . '://';
4334          } elseif ( '/' === $url[0] ) {
4335              $front .= '//';
4336          }
4337  
4338          if ( isset( $parsed['user'] ) ) {
4339              $front .= $parsed['user'];
4340          }
4341  
4342          if ( isset( $parsed['pass'] ) ) {
4343              $front .= ':' . $parsed['pass'];
4344          }
4345  
4346          if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
4347              $front .= '@';
4348          }
4349  
4350          if ( isset( $parsed['host'] ) ) {
4351              $front .= $parsed['host'];
4352          }
4353  
4354          if ( isset( $parsed['port'] ) ) {
4355              $front .= ':' . $parsed['port'];
4356          }
4357  
4358          $end_dirty = str_replace( $front, '', $url );
4359          $end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
4360          $url       = str_replace( $end_dirty, $end_clean, $url );
4361  
4362      }
4363  
4364      if ( '/' === $url[0] ) {
4365          $good_protocol_url = $url;
4366      } else {
4367          if ( ! is_array( $protocols ) ) {
4368              $protocols = wp_allowed_protocols();
4369          }
4370          $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
4371          if ( strtolower( $good_protocol_url ) != strtolower( $url ) ) {
4372              return '';
4373          }
4374      }
4375  
4376      /**
4377       * Filters a string cleaned and escaped for output as a URL.
4378       *
4379       * @since 2.3.0
4380       *
4381       * @param string $good_protocol_url The cleaned URL to be returned.
4382       * @param string $original_url      The URL prior to cleaning.
4383       * @param string $_context          If 'display', replace ampersands and single quotes only.
4384       */
4385      return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
4386  }
4387  
4388  /**
4389   * Performs esc_url() for database usage.
4390   *
4391   * @since 2.8.0
4392   *
4393   * @param string   $url       The URL to be cleaned.
4394   * @param string[] $protocols An array of acceptable protocols.
4395   * @return string The cleaned URL.
4396   */
4397  function esc_url_raw( $url, $protocols = null ) {
4398      return esc_url( $url, $protocols, 'db' );
4399  }
4400  
4401  /**
4402   * Convert entities, while preserving already-encoded entities.
4403   *
4404   * @link https://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
4405   *
4406   * @since 1.2.2
4407   *
4408   * @param string $myHTML The text to be converted.
4409   * @return string Converted text.
4410   */
4411  function htmlentities2( $myHTML ) {
4412      $translation_table              = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
4413      $translation_table[ chr( 38 ) ] = '&';
4414      return preg_replace( '/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&amp;', strtr( $myHTML, $translation_table ) );
4415  }
4416  
4417  /**
4418   * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
4419   *
4420   * Escapes text strings for echoing in JS. It is intended to be used for inline JS
4421   * (in a tag attribute, for example onclick="..."). Note that the strings have to
4422   * be in single quotes. The {@see 'js_escape'} filter is also applied here.
4423   *
4424   * @since 2.8.0
4425   *
4426   * @param string $text The text to be escaped.
4427   * @return string Escaped text.
4428   */
4429  function esc_js( $text ) {
4430      $safe_text = wp_check_invalid_utf8( $text );
4431      $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
4432      $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
4433      $safe_text = str_replace( "\r", '', $safe_text );
4434      $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
4435      /**
4436       * Filters a string cleaned and escaped for output in JavaScript.
4437       *
4438       * Text passed to esc_js() is stripped of invalid or special characters,
4439       * and properly slashed for output.
4440       *
4441       * @since 2.0.6
4442       *
4443       * @param string $safe_text The text after it has been escaped.
4444       * @param string $text      The text prior to being escaped.
4445       */
4446      return apply_filters( 'js_escape', $safe_text, $text );
4447  }
4448  
4449  /**
4450   * Escaping for HTML blocks.
4451   *
4452   * @since 2.8.0
4453   *
4454   * @param string $text
4455   * @return string
4456   */
4457  function esc_html( $text ) {
4458      $safe_text = wp_check_invalid_utf8( $text );
4459      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
4460      /**
4461       * Filters a string cleaned and escaped for output in HTML.
4462       *
4463       * Text passed to esc_html() is stripped of invalid or special characters
4464       * before output.
4465       *
4466       * @since 2.8.0
4467       *
4468       * @param string $safe_text The text after it has been escaped.
4469       * @param string $text      The text prior to being escaped.
4470       */
4471      return apply_filters( 'esc_html', $safe_text, $text );
4472  }
4473  
4474  /**
4475   * Escaping for HTML attributes.
4476   *
4477   * @since 2.8.0
4478   *
4479   * @param string $text
4480   * @return string
4481   */
4482  function esc_attr( $text ) {
4483      $safe_text = wp_check_invalid_utf8( $text );
4484      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
4485      /**
4486       * Filters a string cleaned and escaped for output in an HTML attribute.
4487       *
4488       * Text passed to esc_attr() is stripped of invalid or special characters
4489       * before output.
4490       *
4491       * @since 2.0.6
4492       *
4493       * @param string $safe_text The text after it has been escaped.
4494       * @param string $text      The text prior to being escaped.
4495       */
4496      return apply_filters( 'attribute_escape', $safe_text, $text );
4497  }
4498  
4499  /**
4500   * Escaping for textarea values.
4501   *
4502   * @since 3.1.0
4503   *
4504   * @param string $text
4505   * @return string
4506   */
4507  function esc_textarea( $text ) {
4508      $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
4509      /**
4510       * Filters a string cleaned and escaped for output in a textarea element.
4511       *
4512       * @since 3.1.0
4513       *
4514       * @param string $safe_text The text after it has been escaped.
4515       * @param string $text      The text prior to being escaped.
4516       */
4517      return apply_filters( 'esc_textarea', $safe_text, $text );
4518  }
4519  
4520  /**
4521   * Escape an HTML tag name.
4522   *
4523   * @since 2.5.0
4524   *
4525   * @param string $tag_name
4526   * @return string
4527   */
4528  function tag_escape( $tag_name ) {
4529      $safe_tag = strtolower( preg_replace( '/[^a-zA-Z0-9_:]/', '', $tag_name ) );
4530      /**
4531       * Filters a string cleaned and escaped for output as an HTML tag.
4532       *
4533       * @since 2.8.0
4534       *
4535       * @param string $safe_tag The tag name after it has been escaped.
4536       * @param string $tag_name The text before it was escaped.
4537       */
4538      return apply_filters( 'tag_escape', $safe_tag, $tag_name );
4539  }
4540  
4541  /**
4542   * Convert full URL paths to absolute paths.
4543   *
4544   * Removes the http or https protocols and the domain. Keeps the path '/' at the
4545   * beginning, so it isn't a true relative link, but from the web root base.
4546   *
4547   * @since 2.1.0
4548   * @since 4.1.0 Support was added for relative URLs.
4549   *
4550   * @param string $link Full URL path.
4551   * @return string Absolute path.
4552   */
4553  function wp_make_link_relative( $link ) {
4554      return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
4555  }
4556  
4557  /**
4558   * Sanitises various option values based on the nature of the option.
4559   *
4560   * This is basically a switch statement which will pass $value through a number
4561   * of functions depending on the $option.
4562   *
4563   * @since 2.0.5
4564   *
4565   * @global wpdb $wpdb WordPress database abstraction object.
4566   *
4567   * @param string $option The name of the option.
4568   * @param string $value  The unsanitised value.
4569   * @return string Sanitized value.
4570   */
4571  function sanitize_option( $option, $value ) {
4572      global $wpdb;
4573  
4574      $original_value = $value;
4575      $error          = '';
4576  
4577      switch ( $option ) {
4578          case 'admin_email':
4579          case 'new_admin_email':
4580              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4581              if ( is_wp_error( $value ) ) {
4582                  $error = $value->get_error_message();
4583              } else {
4584                  $value = sanitize_email( $value );
4585                  if ( ! is_email( $value ) ) {
4586                      $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
4587                  }
4588              }
4589              break;
4590  
4591          case 'thumbnail_size_w':
4592          case 'thumbnail_size_h':
4593          case 'medium_size_w':
4594          case 'medium_size_h':
4595          case 'medium_large_size_w':
4596          case 'medium_large_size_h':
4597          case 'large_size_w':
4598          case 'large_size_h':
4599          case 'mailserver_port':
4600          case 'comment_max_links':
4601          case 'page_on_front':
4602          case 'page_for_posts':
4603          case 'rss_excerpt_length':
4604          case 'default_category':
4605          case 'default_email_category':
4606          case 'default_link_category':
4607          case 'close_comments_days_old':
4608          case 'comments_per_page':
4609          case 'thread_comments_depth':
4610          case 'users_can_register':
4611          case 'start_of_week':
4612          case 'site_icon':
4613              $value = absint( $value );
4614              break;
4615  
4616          case 'posts_per_page':
4617          case 'posts_per_rss':
4618              $value = (int) $value;
4619              if ( empty( $value ) ) {
4620                  $value = 1;
4621              }
4622              if ( $value < -1 ) {
4623                  $value = abs( $value );
4624              }
4625              break;
4626  
4627          case 'default_ping_status':
4628          case 'default_comment_status':
4629              // Options that if not there have 0 value but need to be something like "closed".
4630              if ( '0' == $value || '' == $value ) {
4631                  $value = 'closed';
4632              }
4633              break;
4634  
4635          case 'blogdescription':
4636          case 'blogname':
4637              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4638              if ( $value !== $original_value ) {
4639                  $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', wp_encode_emoji( $original_value ) );
4640              }
4641  
4642              if ( is_wp_error( $value ) ) {
4643                  $error = $value->get_error_message();
4644              } else {
4645                  $value = esc_html( $value );
4646              }
4647              break;
4648  
4649          case 'blog_charset':
4650              $value = preg_replace( '/[^a-zA-Z0-9_-]/', '', $value ); // Strips slashes.
4651              break;
4652  
4653          case 'blog_public':
4654              // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
4655              if ( null === $value ) {
4656                  $value = 1;
4657              } else {
4658                  $value = intval( $value );
4659              }
4660              break;
4661  
4662          case 'date_format':
4663          case 'time_format':
4664          case 'mailserver_url':
4665          case 'mailserver_login':
4666          case 'mailserver_pass':
4667          case 'upload_path':
4668              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4669              if ( is_wp_error( $value ) ) {
4670                  $error = $value->get_error_message();
4671              } else {
4672                  $value = strip_tags( $value );
4673                  $value = wp_kses_data( $value );
4674              }
4675              break;
4676  
4677          case 'ping_sites':
4678              $value = explode( "\n", $value );
4679              $value = array_filter( array_map( 'trim', $value ) );
4680              $value = array_filter( array_map( 'esc_url_raw', $value ) );
4681              $value = implode( "\n", $value );
4682              break;
4683  
4684          case 'gmt_offset':
4685              $value = preg_replace( '/[^0-9:.-]/', '', $value ); // Strips slashes.
4686              break;
4687  
4688          case 'siteurl':
4689              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4690              if ( is_wp_error( $value ) ) {
4691                  $error = $value->get_error_message();
4692              } else {
4693                  if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
4694                      $value = esc_url_raw( $value );
4695                  } else {
4696                      $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
4697                  }
4698              }
4699              break;
4700  
4701          case 'home':
4702              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4703              if ( is_wp_error( $value ) ) {
4704                  $error = $value->get_error_message();
4705              } else {
4706                  if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
4707                      $value = esc_url_raw( $value );
4708                  } else {
4709                      $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
4710                  }
4711              }
4712              break;
4713  
4714          case 'WPLANG':
4715              $allowed = get_available_languages();
4716              if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
4717                  $allowed[] = WPLANG;
4718              }
4719              if ( ! in_array( $value, $allowed, true ) && ! empty( $value ) ) {
4720                  $value = get_option( $option );
4721              }
4722              break;
4723  
4724          case 'illegal_names':
4725              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4726              if ( is_wp_error( $value ) ) {
4727                  $error = $value->get_error_message();
4728              } else {
4729                  if ( ! is_array( $value ) ) {
4730                      $value = explode( ' ', $value );
4731                  }
4732  
4733                  $value = array_values( array_filter( array_map( 'trim', $value ) ) );
4734  
4735                  if ( ! $value ) {
4736                      $value = '';
4737                  }
4738              }
4739              break;
4740  
4741          case 'limited_email_domains':
4742          case 'banned_email_domains':
4743              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4744              if ( is_wp_error( $value ) ) {
4745                  $error = $value->get_error_message();
4746              } else {
4747                  if ( ! is_array( $value ) ) {
4748                      $value = explode( "\n", $value );
4749                  }
4750  
4751                  $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
4752                  $value   = array();
4753  
4754                  foreach ( $domains as $domain ) {
4755                      if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
4756                          $value[] = $domain;
4757                      }
4758                  }
4759                  if ( ! $value ) {
4760                      $value = '';
4761                  }
4762              }
4763              break;
4764  
4765          case 'timezone_string':
4766              $allowed_zones = timezone_identifiers_list();
4767              if ( ! in_array( $value, $allowed_zones, true ) && ! empty( $value ) ) {
4768                  $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
4769              }
4770              break;
4771  
4772          case 'permalink_structure':
4773          case 'category_base':
4774          case 'tag_base':
4775              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4776              if ( is_wp_error( $value ) ) {
4777                  $error = $value->get_error_message();
4778              } else {
4779                  $value = esc_url_raw( $value );
4780                  $value = str_replace( 'http://', '', $value );
4781              }
4782  
4783              if ( 'permalink_structure' === $option && '' !== $value && ! preg_match( '/%[^\/%]+%/', $value ) ) {
4784                  $error = sprintf(
4785                      /* translators: %s: Documentation URL. */
4786                      __( 'A structure tag is required when using custom permalinks. <a href="%s">Learn more</a>' ),
4787                      __( 'https://wordpress.org/support/article/using-permalinks/#choosing-your-permalink-structure' )
4788                  );
4789              }
4790              break;
4791  
4792          case 'default_role':
4793              if ( ! get_role( $value ) && get_role( 'subscriber' ) ) {
4794                  $value = 'subscriber';
4795              }
4796              break;
4797  
4798          case 'moderation_keys':
4799          case 'blacklist_keys':
4800              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4801              if ( is_wp_error( $value ) ) {
4802                  $error = $value->get_error_message();
4803              } else {
4804                  $value = explode( "\n", $value );
4805                  $value = array_filter( array_map( 'trim', $value ) );
4806                  $value = array_unique( $value );
4807                  $value = implode( "\n", $value );
4808              }
4809              break;
4810      }
4811  
4812      if ( ! empty( $error ) ) {
4813          $value = get_option( $option );
4814          if ( function_exists( 'add_settings_error' ) ) {
4815              add_settings_error( $option, "invalid_{$option}", $error );
4816          }
4817      }
4818  
4819      /**
4820       * Filters an option value following sanitization.
4821       *
4822       * @since 2.3.0
4823       * @since 4.3.0 Added the `$original_value` parameter.
4824       *
4825       * @param string $value          The sanitized option value.
4826       * @param string $option         The option name.
4827       * @param string $original_value The original value passed to the function.
4828       */
4829      return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
4830  }
4831  
4832  /**
4833   * Maps a function to all non-iterable elements of an array or an object.
4834   *
4835   * This is similar to `array_walk_recursive()` but acts upon objects too.
4836   *
4837   * @since 4.4.0
4838   *
4839   * @param mixed    $value    The array, object, or scalar.
4840   * @param callable $callback The function to map onto $value.
4841   * @return mixed The value with the callback applied to all non-arrays and non-objects inside it.
4842   */
4843  function map_deep( $value, $callback ) {
4844      if ( is_array( $value ) ) {
4845          foreach ( $value as $index => $item ) {
4846              $value[ $index ] = map_deep( $item, $callback );
4847          }
4848      } elseif ( is_object( $value ) ) {
4849          $object_vars = get_object_vars( $value );
4850          foreach ( $object_vars as $property_name => $property_value ) {
4851              $value->$property_name = map_deep( $property_value, $callback );
4852          }
4853      } else {
4854          $value = call_user_func( $callback, $value );
4855      }
4856  
4857      return $value;
4858  }
4859  
4860  /**
4861   * Parses a string into variables to be stored in an array.
4862   *
4863   *
4864   * @since 2.2.1
4865   *
4866   * @param string $string The string to be parsed.
4867   * @param array  $array  Variables will be stored in this array.
4868   */
4869  function wp_parse_str( $string, &$array ) {
4870      parse_str( $string, $array );
4871  
4872      /**
4873       * Filters the array of variables derived from a parsed string.
4874       *
4875       * @since 2.3.0
4876       *
4877       * @param array $array The array populated with variables.
4878       */
4879      $array = apply_filters( 'wp_parse_str', $array );
4880  }
4881  
4882  /**
4883   * Convert lone less than signs.
4884   *
4885   * KSES already converts lone greater than signs.
4886   *
4887   * @since 2.3.0
4888   *
4889   * @param string $text Text to be converted.
4890   * @return string Converted text.
4891   */
4892  function wp_pre_kses_less_than( $text ) {
4893      return preg_replace_callback( '%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text );
4894  }
4895  
4896  /**
4897   * Callback function used by preg_replace.
4898   *
4899   * @since 2.3.0
4900   *
4901   * @param array $matches Populated by matches to preg_replace.
4902   * @return string The text returned after esc_html if needed.
4903   */
4904  function wp_pre_kses_less_than_callback( $matches ) {
4905      if ( false === strpos( $matches[0], '>' ) ) {
4906          return esc_html( $matches[0] );
4907      }
4908      return $matches[0];
4909  }
4910  
4911  /**
4912   * Remove non-allowable HTML from parsed block attribute values when filtering
4913   * in the post context.
4914   *
4915   * @since 5.3.1
4916   *
4917   * @param string         $string            Content to be run through KSES.
4918   * @param array[]|string $allowed_html      An array of allowed HTML elements
4919   *                                          and attributes, or a context name
4920   *                                          such as 'post'.
4921   * @param string[]       $allowed_protocols Array of allowed URL protocols.
4922   * @return string Filtered text to run through KSES.
4923   */
4924  function wp_pre_kses_block_attributes( $string, $allowed_html, $allowed_protocols ) {
4925      /*
4926       * `filter_block_content` is expected to call `wp_kses`. Temporarily remove
4927       * the filter to avoid recursion.
4928       */
4929      remove_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10 );
4930      $string = filter_block_content( $string, $allowed_html, $allowed_protocols );
4931      add_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10, 3 );
4932  
4933      return $string;
4934  }
4935  
4936  /**
4937   * WordPress implementation of PHP sprintf() with filters.
4938   *
4939   * @since 2.5.0
4940   * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
4941   *              by adding it to the function signature.
4942   *
4943   * @link https://www.php.net/sprintf
4944   *
4945   * @param string $pattern The string which formatted args are inserted.
4946   * @param mixed  ...$args Arguments to be formatted into the $pattern string.
4947   * @return string The formatted string.
4948   */
4949  function wp_sprintf( $pattern, ...$args ) {
4950      $len       = strlen( $pattern );
4951      $start     = 0;
4952      $result    = '';
4953      $arg_index = 0;
4954      while ( $len > $start ) {
4955          // Last character: append and break.
4956          if ( strlen( $pattern ) - 1 == $start ) {
4957              $result .= substr( $pattern, -1 );
4958              break;
4959          }
4960  
4961          // Literal %: append and continue.
4962          if ( substr( $pattern, $start, 2 ) == '%%' ) {
4963              $start  += 2;
4964              $result .= '%';
4965              continue;
4966          }
4967  
4968          // Get fragment before next %.
4969          $end = strpos( $pattern, '%', $start + 1 );
4970          if ( false === $end ) {
4971              $end = $len;
4972          }
4973          $fragment = substr( $pattern, $start, $end - $start );
4974  
4975          // Fragment has a specifier.
4976          if ( '%' === $pattern[ $start ] ) {
4977              // Find numbered arguments or take the next one in order.
4978              if ( preg_match( '/^%(\d+)\$/', $fragment, $matches ) ) {
4979                  $index    = $matches[1] - 1; // 0-based array vs 1-based sprintf() arguments.
4980                  $arg      = isset( $args[ $index ] ) ? $args[ $index ] : '';
4981                  $fragment = str_replace( "%{$matches[1]}$", '%', $fragment );
4982              } else {
4983                  $arg = isset( $args[ $arg_index ] ) ? $args[ $arg_index ] : '';
4984                  ++$arg_index;
4985              }
4986  
4987              /**
4988               * Filters a fragment from the pattern passed to wp_sprintf().
4989               *
4990               * If the fragment is unchanged, then sprintf() will be run on the fragment.
4991               *
4992               * @since 2.5.0
4993               *
4994               * @param string $fragment A fragment from the pattern.
4995               * @param string $arg      The argument.
4996               */
4997              $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
4998              if ( $_fragment != $fragment ) {
4999                  $fragment = $_fragment;
5000              } else {
5001                  $fragment = sprintf( $fragment, strval( $arg ) );
5002              }
5003          }
5004  
5005          // Append to result and move to next fragment.
5006          $result .= $fragment;
5007          $start   = $end;
5008      }
5009  
5010      return $result;
5011  }
5012  
5013  /**
5014   * Localize list items before the rest of the content.
5015   *
5016   * The '%l' must be at the first characters can then contain the rest of the
5017   * content. The list items will have ', ', ', and', and ' and ' added depending
5018   * on the amount of list items in the $args parameter.
5019   *
5020   * @since 2.5.0
5021   *
5022   * @param string $pattern Content containing '%l' at the beginning.
5023   * @param array  $args    List items to prepend to the content and replace '%l'.
5024   * @return string Localized list items and rest of the content.
5025   */
5026  function wp_sprintf_l( $pattern, $args ) {
5027      // Not a match.
5028      if ( substr( $pattern, 0, 2 ) != '%l' ) {
5029          return $pattern;
5030      }
5031  
5032      // Nothing to work with.
5033      if ( empty( $args ) ) {
5034          return '';
5035      }
5036  
5037      /**
5038       * Filters the translated delimiters used by wp_sprintf_l().
5039       * Placeholders (%s) are included to assist translators and then
5040       * removed before the array of strings reaches the filter.
5041       *
5042       * Please note: Ampersands and entities should be avoided here.
5043       *
5044       * @since 2.5.0
5045       *
5046       * @param array $delimiters An array of translated delimiters.
5047       */
5048      $l = apply_filters(
5049          'wp_sprintf_l',
5050          array(
5051              /* translators: Used to join items in a list with more than 2 items. */
5052              'between'          => sprintf( __( '%1$s, %2$s' ), '', '' ),
5053              /* translators: Used to join last two items in a list with more than 2 times. */
5054              'between_last_two' => sprintf( __( '%1$s, and %2$s' ), '', '' ),
5055              /* translators: Used to join items in a list with only 2 items. */
5056              'between_only_two' => sprintf( __( '%1$s and %2$s' ), '', '' ),
5057          )
5058      );
5059  
5060      $args   = (array) $args;
5061      $result = array_shift( $args );
5062      if ( count( $args ) == 1 ) {
5063          $result .= $l['between_only_two'] . array_shift( $args );
5064      }
5065  
5066      // Loop when more than two args.
5067      $i = count( $args );
5068      while ( $i ) {
5069          $arg = array_shift( $args );
5070          $i--;
5071          if ( 0 == $i ) {
5072              $result .= $l['between_last_two'] . $arg;
5073          } else {
5074              $result .= $l['between'] . $arg;
5075          }
5076      }
5077  
5078      return $result . substr( $pattern, 2 );
5079  }
5080  
5081  /**
5082   * Safely extracts not more than the first $count characters from html string.
5083   *
5084   * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
5085   * be counted as one character. For example &amp; will be counted as 4, &lt; as
5086   * 3, etc.
5087   *
5088   * @since 2.5.0
5089   *
5090   * @param string $str   String to get the excerpt from.
5091   * @param int    $count Maximum number of characters to take.
5092   * @param string $more  Optional. What to append if $str needs to be trimmed. Defaults to empty string.
5093   * @return string The excerpt.
5094   */
5095  function wp_html_excerpt( $str, $count, $more = null ) {
5096      if ( null === $more ) {
5097          $more = '';
5098      }
5099  
5100      $str     = wp_strip_all_tags( $str, true );
5101      $excerpt = mb_substr( $str, 0, $count );
5102  
5103      // Remove part of an entity at the end.
5104      $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
5105      if ( $str != $excerpt ) {
5106          $excerpt = trim( $excerpt ) . $more;
5107      }
5108  
5109      return $excerpt;
5110  }
5111  
5112  /**
5113   * Add a Base url to relative links in passed content.
5114   *
5115   * By default it supports the 'src' and 'href' attributes. However this can be
5116   * changed via the 3rd param.
5117   *
5118   * @since 2.7.0
5119   *
5120   * @global string $_links_add_base
5121   *
5122   * @param string $content String to search for links in.
5123   * @param string $base    The base URL to prefix to links.
5124   * @param array  $attrs   The attributes which should be processed.
5125   * @return string The processed content.
5126   */
5127  function links_add_base_url( $content, $base, $attrs = array( 'src', 'href' ) ) {
5128      global $_links_add_base;
5129      $_links_add_base = $base;
5130      $attrs           = implode( '|', (array) $attrs );
5131      return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
5132  }
5133  
5134  /**
5135   * Callback to add a base url to relative links in passed content.
5136   *
5137   * @since 2.7.0
5138   * @access private
5139   *
5140   * @global string $_links_add_base
5141   *
5142   * @param string $m The matched link.
5143   * @return string The processed link.
5144   */
5145  function _links_add_base( $m ) {
5146      global $_links_add_base;
5147      // 1 = attribute name  2 = quotation mark  3 = URL.
5148      return $m[1] . '=' . $m[2] .
5149          ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols(), true ) ?
5150              $m[3] :
5151              WP_Http::make_absolute_url( $m[3], $_links_add_base )
5152          )
5153          . $m[2];
5154  }
5155  
5156  /**
5157   * Adds a Target attribute to all links in passed content.
5158   *
5159   * This function by default only applies to `<a>` tags, however this can be
5160   * modified by the 3rd param.
5161   *
5162   * *NOTE:* Any current target attributed will be stripped and replaced.
5163   *
5164   * @since 2.7.0
5165   *
5166   * @global string $_links_add_target
5167   *
5168   * @param string   $content String to search for links in.
5169   * @param string   $target  The Target to add to the links.
5170   * @param string[] $tags    An array of tags to apply to.
5171   * @return string The processed content.
5172   */
5173  function links_add_target( $content, $target = '_blank', $tags = array( 'a' ) ) {
5174      global $_links_add_target;
5175      $_links_add_target = $target;
5176      $tags              = implode( '|', (array) $tags );
5177      return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
5178  }
5179  
5180  /**
5181   * Callback to add a target attribute to all links in passed content.
5182   *
5183   * @since 2.7.0
5184   * @access private
5185   *
5186   * @global string $_links_add_target
5187   *
5188   * @param string $m The matched link.
5189   * @return string The processed link.
5190   */
5191  function _links_add_target( $m ) {
5192      global $_links_add_target;
5193      $tag  = $m[1];
5194      $link = preg_replace( '|( target=([\'"])(.*?)\2)|i', '', $m[2] );
5195      return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
5196  }
5197  
5198  /**
5199   * Normalize EOL characters and strip duplicate whitespace.
5200   *
5201   * @since 2.7.0
5202   *
5203   * @param string $str The string to normalize.
5204   * @return string The normalized string.
5205   */
5206  function normalize_whitespace( $str ) {
5207      $str = trim( $str );
5208      $str = str_replace( "\r", "\n", $str );
5209      $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
5210      return $str;
5211  }
5212  
5213  /**
5214   * Properly strip all HTML tags including script and style
5215   *
5216   * This differs from strip_tags() because it removes the contents of
5217   * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
5218   * will return 'something'. wp_strip_all_tags will return ''
5219   *
5220   * @since 2.9.0
5221   *
5222   * @param string $string        String containing HTML tags
5223   * @param bool   $remove_breaks Optional. Whether to remove left over line breaks and white space chars
5224   * @return string The processed string.
5225   */
5226  function wp_strip_all_tags( $string, $remove_breaks = false ) {
5227      $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
5228      $string = strip_tags( $string );
5229  
5230      if ( $remove_breaks ) {
5231          $string = preg_replace( '/[\r\n\t ]+/', ' ', $string );
5232      }
5233  
5234      return trim( $string );
5235  }
5236  
5237  /**
5238   * Sanitizes a string from user input or from the database.
5239   *
5240   * - Checks for invalid UTF-8,
5241   * - Converts single `<` characters to entities
5242   * - Strips all tags
5243   * - Removes line breaks, tabs, and extra whitespace
5244   * - Strips octets
5245   *
5246   * @since 2.9.0
5247   *
5248   * @see sanitize_textarea_field()
5249   * @see wp_check_invalid_utf8()
5250   * @see wp_strip_all_tags()
5251   *
5252   * @param string $str String to sanitize.
5253   * @return string Sanitized string.
5254   */
5255  function sanitize_text_field( $str ) {
5256      $filtered = _sanitize_text_fields( $str, false );
5257  
5258      /**
5259       * Filters a sanitized text field string.
5260       *
5261       * @since 2.9.0
5262       *
5263       * @param string $filtered The sanitized string.
5264       * @param string $str      The string prior to being sanitized.
5265       */
5266      return apply_filters( 'sanitize_text_field', $filtered, $str );
5267  }
5268  
5269  /**
5270   * Sanitizes a multiline string from user input or from the database.
5271   *
5272   * The function is like sanitize_text_field(), but preserves
5273   * new lines (\n) and other whitespace, which are legitimate
5274   * input in textarea elements.
5275   *
5276   * @see sanitize_text_field()
5277   *
5278   * @since 4.7.0
5279   *
5280   * @param string $str String to sanitize.
5281   * @return string Sanitized string.
5282   */
5283  function sanitize_textarea_field( $str ) {
5284      $filtered = _sanitize_text_fields( $str, true );
5285  
5286      /**
5287       * Filters a sanitized textarea field string.
5288       *
5289       * @since 4.7.0
5290       *
5291       * @param string $filtered The sanitized string.
5292       * @param string $str      The string prior to being sanitized.
5293       */
5294      return apply_filters( 'sanitize_textarea_field', $filtered, $str );
5295  }
5296  
5297  /**
5298   * Internal helper function to sanitize a string from user input or from the db
5299   *
5300   * @since 4.7.0
5301   * @access private
5302   *
5303   * @param string $str String to sanitize.
5304   * @param bool $keep_newlines optional Whether to keep newlines. Default: false.
5305   * @return string Sanitized string.
5306   */
5307  function _sanitize_text_fields( $str, $keep_newlines = false ) {
5308      if ( is_object( $str ) || is_array( $str ) ) {
5309          return '';
5310      }
5311  
5312      $str = (string) $str;
5313  
5314      $filtered = wp_check_invalid_utf8( $str );
5315  
5316      if ( strpos( $filtered, '<' ) !== false ) {
5317          $filtered = wp_pre_kses_less_than( $filtered );
5318          // This will strip extra whitespace for us.
5319          $filtered = wp_strip_all_tags( $filtered, false );
5320  
5321          // Use HTML entities in a special case to make sure no later
5322          // newline stripping stage could lead to a functional tag.
5323          $filtered = str_replace( "<\n", "&lt;\n", $filtered );
5324      }
5325  
5326      if ( ! $keep_newlines ) {
5327          $filtered = preg_replace( '/[\r\n\t ]+/', ' ', $filtered );
5328      }
5329      $filtered = trim( $filtered );
5330  
5331      $found = false;
5332      while ( preg_match( '/%[a-f0-9]{2}/i', $filtered, $match ) ) {
5333          $filtered = str_replace( $match[0], '', $filtered );
5334          $found    = true;
5335      }
5336  
5337      if ( $found ) {
5338          // Strip out the whitespace that may now exist after removing the octets.
5339          $filtered = trim( preg_replace( '/ +/', ' ', $filtered ) );
5340      }
5341  
5342      return $filtered;
5343  }
5344  
5345  /**
5346   * i18n friendly version of basename()
5347   *
5348   * @since 3.1.0
5349   *
5350   * @param string $path   A path.
5351   * @param string $suffix If the filename ends in suffix this will also be cut off.
5352</