wp_replace_in_html_tags

Replace characters or phrases within HTML elements only.

Description

(string) wp_replace_in_html_tags( (string) $haystack, (array) $replace_pairs ); 

Returns (string)

The formatted text.

Parameters (2)

0. $haystack (string)
The text which has to be formatted.
1. $replace_pairs (array)
In the form array('from' => to,, ...).

Usage

  1. if ( !function_exists( 'wp_replace_in_html_tags' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // The text which has to be formatted. 
  5. $haystack = ''; 
  6.  
  7. // In the form array('from' => 'to', ...). 
  8. $replace_pairs = array(); 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = wp_replace_in_html_tags($haystack, $replace_pairs); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function wp_replace_in_html_tags( $haystack, $replace_pairs ) { 
  2. // Find all elements. 
  3. $textarr = wp_html_split( $haystack ); 
  4. $changed = false; 
  5.  
  6. // Optimize when searching for one item. 
  7. if ( 1 === count( $replace_pairs ) ) { 
  8. // Extract $needle and $replace. 
  9. foreach ( $replace_pairs as $needle => $replace ); 
  10.  
  11. // Loop through delimiters (elements) only. 
  12. for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) { 
  13. if ( false !== strpos( $textarr[$i], $needle ) ) { 
  14. $textarr[$i] = str_replace( $needle, $replace, $textarr[$i] ); 
  15. $changed = true; 
  16. } else { 
  17. // Extract all $needles. 
  18. $needles = array_keys( $replace_pairs ); 
  19.  
  20. // Loop through delimiters (elements) only. 
  21. for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) { 
  22. foreach ( $needles as $needle ) { 
  23. if ( false !== strpos( $textarr[$i], $needle ) ) { 
  24. $textarr[$i] = strtr( $textarr[$i], $replace_pairs ); 
  25. $changed = true; 
  26. // After one strtr() break out of the foreach loop and look at next element. 
  27. break; 
  28.  
  29. if ( $changed ) { 
  30. $haystack = implode( $textarr ); 
  31.  
  32. return $haystack;