The force_balance_tags() WordPress PHP function balances the HTML tags in a given string of text. This function ensures that all opened HTML tags in the text are properly closed.
Usage
Here’s a basic usage of the function:
$text = "<b>Some text"; $balanced_text = force_balance_tags($text);
In the above code, $balanced_text
will return <b>Some text</b>
, as the function adds a closing </b>
tag to balance the initially opened <b>
tag.
Parameters
- $text (string) – The text in which HTML tags are to be balanced.
More information
See WordPress Developer Resources: force_balance_tags()
This function has been available since WordPress version 2.0.4. No depreciation has been noted up until now.
Examples
Balancing Simple Text
In this example, we have a text string with a missing closing tag for the bold element (<b>
).
$text = "<b>Some bold text"; $balanced_text = force_balance_tags($text); // The output will be "<b>Some bold text</b>"
Nested Tags
When there are nested tags, force_balance_tags() can balance those as well.
$text = "<div><p>Some text"; $balanced_text = force_balance_tags($text); // The output will be "<div><p>Some text</p></div>"
Multiple Unbalanced Tags
When there are multiple unbalanced tags, force_balance_tags() can handle them all.
$text = "<div><p>Some text<b>Bold text"; $balanced_text = force_balance_tags($text); // The output will be "<div><p>Some text<b>Bold text</b></p></div>"
Self-closing Tags
force_balance_tags() does not affect self-closing tags.
$text = "<div><img src='image.jpg'>"; $balanced_text = force_balance_tags($text); // The output will be "<div><img src='image.jpg'></div>"
No Tags
If there are no tags in the string, force_balance_tags() does not alter the string.
$text = "Just some text"; $balanced_text = force_balance_tags($text); // The output will be "Just some text"