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

Replaces characters or phrases within HTML elements only.

Parameters

$haystackstringrequired
The text which has to be formatted.
$replace_pairsarrayrequired
In the form array('from' => 'to', …).

Return

string The formatted text.

Source

function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
	// Find all elements.
	$textarr = wp_html_split( $haystack );
	$changed = false;

	// Optimize when searching for one item.
	if ( 1 === count( $replace_pairs ) ) {
		// Extract $needle and $replace.
		foreach ( $replace_pairs as $needle => $replace ) {
		}

		// Loop through delimiters (elements) only.
		for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
			if ( str_contains( $textarr[ $i ], $needle ) ) {
				$textarr[ $i ] = str_replace( $needle, $replace, $textarr[ $i ] );
				$changed       = true;
			}
		}
	} else {
		// Extract all $needles.
		$needles = array_keys( $replace_pairs );

		// Loop through delimiters (elements) only.
		for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
			foreach ( $needles as $needle ) {
				if ( str_contains( $textarr[ $i ], $needle ) ) {
					$textarr[ $i ] = strtr( $textarr[ $i ], $replace_pairs );
					$changed       = true;
					// After one strtr() break out of the foreach loop and look at next element.
					break;
				}
			}
		}
	}

	if ( $changed ) {
		$haystack = implode( $textarr );
	}

	return $haystack;
}

Changelog

VersionDescription
4.2.3Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Replace “products” with “services” in text

    $content = 'Welcome to our website! We offer a variety of products.';
    
    $replacements = array(
      'products' => 'services', // Replace "products" with "services"
    );
    
    $new_content = wp_replace_in_html_tags($content, $replacements);
    
    echo $new_content;

    Output:
    Welcome to our website! We offer a variety of services.

You must log in before being able to contribute a note or feedback.