balanceTags()WP 0.71

Fixes incorrectly-entered XHTML (HTML) tags.

The function first checks the option use_balanceTags, if it is disabled, the function will do nothing. To make the function work in any case you need to set the second parameter to $force=true.

1 time — 0.0001741 sec (fast) | 50000 times — 0.37 sec (very fast) | PHP 7.4.8, WP 5.8

No Hooks.

Returns

String. Formatted (balansed) text.

Usage

<?php balanceTags( $text, $force ); ?>
$text(string) (required)
The string in which XHTML (HTML) tags need to be fixed.
Default: ''
$force(boolean)
true — the function will fix tags in any case. false — the function will work only if the option is enabled in the settings.
Default: false

Examples

0

#1 Auto-close HTML tags

An example of how the function reverses improperly used html tags and how it closes tags that were not closed:

$text = "<p><b>This is text in which</p></b> html tags are not balanced.
<p>I.e. there are some that open, but then do not close, which can
lead to problems. Use the function <strong>balanceTags()."

echo htmlspecialchars( balanceTags($text, 1) );

We get it:

<p><b>This is text in which</b></p> html tags are not balanced.
<p>I.e. there are some that open but then do not close, which can lead to problems. Use function <strong>balanceTags().</strong></p>

One more example - Unclosed LI tags:

$html = '<ul>
  <li>this
  <li>is
  <li>a
  <li>list
</ul>';

echo balanceTags( $html, true );

Will output this HTML:

<ul>
  <li>this
  </li><li>is
  </li><li>a
  </li><li>list
</li></ul>

Changelog

Since 0.71 Introduced.

balanceTags() code WP 6.9

function balanceTags( $text, $force = false ) {  // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
	if ( $force || 1 === (int) get_option( 'use_balanceTags' ) ) {
		return force_balance_tags( $text );
	} else {
		return $text;
	}
}