wppaste
WordPress

force_balance_tags( string $text ): string

Since
2.0.4, 5.3.0
Source
wp-includes/formatting.php:2592
Balances tags of string using a modified stack.

Description

Compatibility

WordPress
since 5.3.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$textstring
Text to be balanced.

Return value

string
Balanced text.

Performance profile

How much work a call to force_balance_tags() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Light

Touches nothing outside its own arguments.

Scaling
Scales with input

The body loops, so the work grows with what you pass in.

Instructions
33

Executed per call on PHP 8.5. The body compiles to 154.

Plugin surface
None

Nothing here hands control to plugin code.

Called by
2

2 places in core call this, so the cost is paid more often than your own code shows.

What one call costs · 1 distinct outcome

One number would be a lie: the work depends on which branch runs. These are every distinct cost force_balance_tags() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
!preg_match()33preg_match(), array_pop()

Across PHP versions

PHPCompiledExecutedBranchesNotes
8.6-dev1543319
8.51543319
8.4154331928 fewer instructions than PHP 8.3
8.31824519
8.218245191 more instruction than PHP 8.1
8.118145192 fewer instructions than PHP 7.4
7.41834519

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Uses · 1

Used by · 2

Source code

function force_balance_tags( $text ) {	$tagstack  = array();	$stacksize = 0;	$tagqueue  = '';	$newtext   = '';	// Known single-entity/self-closing tags.	$single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source', 'track', 'wbr' );	// Tags that can be immediately nested within themselves.	$nestable_tags = array( 'article', 'aside', 'blockquote', 'details', 'div', 'figure', 'object', 'q', 'section', 'span' ); 	// WP bug fix for comments - in case you REALLY meant to type '< !--'.	$text = str_replace( '< !--', '<    !--', $text );	// WP bug fix for LOVE <3 (and other situations with '<' before a number).	$text = preg_replace( '#<([0-9]{1})#', '&lt;$1', $text ); 	/**	 * Matches supported tags.	 *	 * To get the pattern as a string without the comments paste into a PHP	 * REPL like `php -a`.	 *	 * @see https://html.spec.whatwg.org/#elements-2	 * @see https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name	 *	 * @example	 * ~# php -a	 * php > $s = [paste copied contents of expression below including parentheses];	 * php > echo $s;	 */	$tag_pattern = (		'#<' . // Start with an opening bracket.		'(/?)' . // Group 1 - If it's a closing tag it'll have a leading slash.		'(' . // Group 2 - Tag name.			// Custom element tags have more lenient rules than HTML tag names.			'(?:[a-z](?:[a-z0-9._]*)-(?:[a-z0-9._-]+)+)' .				'|' .			// Traditional tag rules approximate HTML tag names.			'(?:[\w:]+)' .		')' .		'(?:' .			// We either immediately close the tag with its '>' and have nothing here.			'\s*' .			'(/?)' . // Group 3 - "attributes" for empty tag.				'|' .			// Or we must start with space characters to separate the tag name from the attributes (or whitespace).			'(\s+)' . // Group 4 - Pre-attribute whitespace.			'([^>]*)' . // Group 5 - Attributes.		')' .		'>#' // End with a closing bracket.	); 	while ( preg_match( $tag_pattern, $text, $regex ) ) {		$full_match        = $regex[0];		$has_leading_slash = ! empty( $regex[1] );		$tag_name          = $regex[2];		$tag               = strtolower( $tag_name );		$is_single_tag     = in_array( $tag, $single_tags, true );		$pre_attribute_ws  = $regex[4] ?? '';		$attributes        = trim( $regex[5] ?? $regex[3] );		$has_self_closer   = str_ends_with( $attributes, '/' ); 		$newtext .= $tagqueue; 		$i = strpos( $text, $full_match );		$l = strlen( $full_match ); 		// Clear the shifter.		$tagqueue = '';		if ( $has_leading_slash ) { // End tag.			// If too many closing tags.			if ( $stacksize <= 0 ) {				$tag = '';				// Or close to be safe $tag = '/' . $tag. 				// If stacktop value = tag close value, then pop.			} elseif ( $tagstack[ $stacksize - 1 ] === $tag ) { // Found closing tag.				$tag = '</' . $tag . '>'; // Close tag.				array_pop( $tagstack );				--$stacksize;			} else { // Closing tag not at top, search for it.

Changelog

Introduced in 2.0.4. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

5.3.0
Improve accuracy and add support for custom element tags.from the docblock
2.0.4
Introduced.from the docblock

About this page

Parsed data
Generated from the wordpress-develop 7.1.0 tag, from src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.