balanceTags()WP 0.71

Balances tags if forced to, or if the 'use_balanceTags' option is set to true.

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

No Hooks.

Return

String. Balanced text

Usage

balanceTags( $text, $force );
$text(string) (required)
Text to be balanced
$force(true|false)
If true, forces balancing, ignoring the value of the option.
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.4.3

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