| 759 | } |
| 760 | |
| 761 | if ( $changed ) { |
| 762 | $haystack = implode( $textarr ); |
| 763 | } |
| 764 | |
| 765 | return $haystack; |
| 766 | } |
| 767 | |
| 768 | /** |
| 769 | * Replace characters or phrases within the content of selected HTML elements. |
| 770 | * |
| 771 | * @since 4.7.0 |
| 772 | * |
| 773 | * @param string $haystack The text which has to be formatted. |
| 774 | * @param array $tags The tags to replace inside of. |
| 775 | * @param array $replace_pairs In the form array('from' => 'to', ...). |
| 776 | * @return string The formatted text. |
| 777 | */ |
| 778 | function wp_replace_in_selected_html_content( $haystack, $tags, $replace_pairs ) { |
| 779 | // Find all elements. |
| 780 | $textarr = wp_html_split( $haystack ); |
| 781 | $changed = false; |
| 782 | $replacing = 0; |
| 783 | $tag_count = count( $tags ); |
| 784 | |
| 785 | // Optimize when searching for one item. |
| 786 | if ( 1 === count( $replace_pairs ) ) { |
| 787 | // Extract $needle and $replace. |
| 788 | foreach ( $replace_pairs as $needle => $replace ); |
| 789 | |
| 790 | for ( $i = 0, $c = count( $textarr ); $i < $c; $i += 1 ) { |
| 791 | for ( $j = 0; $j < $tag_count; $j++ ) { |
| 792 | if ( 0 === strpos( $textarr[ $i ], '<' . $tags[ $j ] ) ) { |
| 793 | $replacing++; |
| 794 | } elseif ( $textarr[ $i ] === '</' . $tags[ $j ] . '>' ) { |
| 795 | $replacing--; |
| 796 | } |
| 797 | } |
| 798 | if ( $replacing ) { |
| 799 | $textarr[ $i ] = str_replace( $needle, $replace, $textarr[ $i ] ); |
| 800 | $changed = true; |
| 801 | } |
| 802 | } |
| 803 | } else { |
| 804 | // Extract all $needles. |
| 805 | $needles = array_keys( $replace_pairs ); |
| 806 | |
| 807 | // Loop through delimiters (elements) only. |
| 808 | for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) { |
| 809 | foreach ( $needles as $needle ) { |
| 810 | for ( $j = 0; $j < $tag_count; $j++ ) { |
| 811 | if ( 0 === strpos( $textarr[ $i ], '<' . $tags[ $j ] ) ) { |
| 812 | $replacing++; |
| 813 | } elseif ( $textarr[ $i ] === '</' . $tags[ $j ] . '>' ) { |
| 814 | $replacing--; |
| 815 | } |
| 816 | } |
| 817 | if ( $replacing ) { |
| 818 | $textarr[ $i ] = str_replace( $needle, $replace, $textarr[ $i ] ); |
| 819 | $changed = true; |
| 820 | } |
| 821 | } |
| 822 | } |