wppaste
WordPress

WP_HTML_Tag_Processor

Since
6.2.0, 6.2.1, 6.3.2, 6.5.0
Source
wp-includes/html-api/class-wp-html-tag-processor.php:411
Core class used to modify attributes in an HTML document for tags matching a query.

Description

Usage

Use of this class requires three steps:

  1. Create a new class instance with your input HTML document.
  2. Find the tag(s) you are looking for.
  3. Request changes to the attributes in those tag(s).

Example:

$tags = new WP_HTML_Tag_Processor( $html );
if ( $tags->next_tag( 'option' ) ) {
 $tags->set_attribute( 'selected', true );
}

Finding tags

The next_tag() function moves the internal cursor through your input HTML document until it finds a tag meeting any of the supplied restrictions in the optional query argument. If no argument is provided then it will find the next HTML tag, regardless of what kind it is.

If you want to find whatever the next tag is:

$tags->next_tag();
Goal Query
Find any tag. $tags->next_tag();
Find next image tag. $tags->next_tag( array( 'tag_name' => 'img' ) );
Find next image tag (without passing the array). $tags->next_tag( 'img' );
Find next tag containing the fullwidth CSS class. $tags->next_tag( array( 'class_name' => 'fullwidth' ) );
Find next image tag containing the fullwidth CSS class. $tags->next_tag( array( 'tag_name' => 'img', 'class_name' => 'fullwidth' ) );

If a tag was found meeting your criteria then next_tag() will return true and you can proceed to modify it. If it returns false, however, it failed to find the tag and moved the cursor to the end of the file.

Once the cursor reaches the end of the file the processor is done and if you want to reach an earlier tag you will need to recreate the processor and start over, as it's unable to back up or move in reverse.

See the section on bookmarks for an exception to this no-backing-up rule.

Custom queries

Sometimes it's necessary to further inspect an HTML tag than the query syntax here permits. In these cases one may further inspect the search results using the read-only functions provided by the processor or external state or variables.

Example:

// Paint up to the first five DIV or SPAN tags marked with the "jazzy" style.
$remaining_count = 5;
while ( $remaining_count > 0 && $tags->next_tag() ) {
 if (
 ( 'DIV' === $tags->get_tag() || 'SPAN' === $tags->get_tag() ) &&
 'jazzy' === $tags->get_attribute( 'data-style' )
 ) {
 $tags->add_class( 'theme-style-everest-jazz' );
 $remaining_count--;
 }
}

get_attribute() will return null if the attribute wasn't present on the tag when it was called. It may return "" (the empty string) in cases where the attribute was present but its value was empty.
For boolean attributes, those whose name is present but no value is given, it will return true (the only way to set false for an attribute is to remove it).

When matching fails

When next_tag() returns false it could mean different things:

  • The requested tag wasn't found in the input document.
  • The input document ended in the middle of an HTML syntax element.

When a document ends in the middle of a syntax element it will pause the processor. This is to make it possible in the future to extend the input document and proceed - an important requirement for chunked streaming parsing of a document.

Example:

$processor = new WP_HTML_Tag_Processor( 'This <div is="a" partial="token' );
false === $processor->next_tag();

If a special element (see next section) is encountered but no closing tag is found it will count as an incomplete tag. The parser will pause as if the opening tag were incomplete.

Example:

$processor = new WP_HTML_Tag_Processor( '<style>// there could be more styling to come' );
false === $processor->next_tag();

$processor = new WP_HTML_Tag_Processor( '<style>// this is everything</style><div>' );
true === $processor->next_tag( 'DIV' );

Special self-contained elements

Some HTML elements are handled in a special way; their start and end tags act like a void tag. These are special because their contents can't contain HTML markup. Everything inside these elements is handled in a special way and content that appears like HTML tags inside of them isn't. There can be no nesting in these elements.

In the following list, "raw text" means that all of the content in the HTML until the matching closing tag is treated verbatim without any replacements and without any parsing.

  • IFRAME allows no content but requires a closing tag.
  • NOEMBED (deprecated) content is raw text.
  • NOFRAMES (deprecated) content is raw text.
  • SCRIPT content is plaintext apart from legacy rules allowing </script> inside an HTML comment.
  • STYLE content is raw text.
  • TITLE content is plain text but character references are decoded.
  • TEXTAREA content is plain text but character references are decoded.
  • XMP (deprecated) content is raw text.

Modifying HTML attributes for a found tag

Once you've found the start of an opening tag you can modify any number of the attributes on that tag. You can set a new value for an attribute, remove the entire attribute, or do nothing and move on to the next opening tag.

Example:

if ( $tags->next_tag( array( 'class_name' => 'wp-group-block' ) ) ) {
 $tags->set_attribute( 'title', 'This groups the contained content.' );
 $tags->remove_attribute( 'data-test-id' );
}

If set_attribute() is called for an existing attribute it will overwrite the existing value. Similarly, calling remove_attribute() for a non-existing attribute has no effect on the document. Both of these methods are safe to call without knowing if a given attribute exists beforehand.

Modifying CSS classes for a found tag

The tag processor treats the class attribute as a special case.
Because it's a common operation to add or remove CSS classes, this interface adds helper methods to make that easier.

As with attribute values, adding or removing CSS classes is a safe operation that doesn't require checking if the attribute or class exists before making changes. If removing the only class then the entire class attribute will be removed.

Example:

// from <span>Yippee!</span>
// to <span class="is-active">Yippee!</span>
$tags->add_class( 'is-active' );

// from <span class="excited">Yippee!</span>
// to <span class="excited is-active">Yippee!</span>
$tags->add_class( 'is-active' );

// from <span class="is-active heavy-accent">Yippee!</span>
// to <span class="is-active heavy-accent">Yippee!</span>
$tags->add_class( 'is-active' );

// from <input type="text" class="is-active rugby not-disabled" length="24">
// to <input type="text" class="is-active not-disabled" length="24">
$tags->remove_class( 'rugby' );

// from <input type="text" class="rugby" length="24">
// to <input type="text" length="24">
$tags->remove_class( 'rugby' );

// from <input type="text" length="24">
// to `<input type="text" length="24">
$tags->remove_class( 'rugby' );

When class changes are enqueued but a direct change to class is made via set_attribute then the changes to set_attribute (or remove_attribute) will take precedence over those made through add_class and remove_class.

Bookmarks

While scanning through the input HTML document it's possible to set a named bookmark when a particular tag is found. Later on, after continuing to scan other tags, it's possible to seek to one of the set bookmarks and then proceed again from that point forward.

Because bookmarks create processing overhead one should avoid creating too many of them. As a rule, create only bookmarks of known string literal names; avoid creating "mark_{$index}" and so on. It's fine from a performance standpoint to create a bookmark and update it frequently, such as within a loop.

$total_todos = 0;
while ( $p->next_tag( array( 'tag_name' => 'UL', 'class_name' => 'todo' ) ) ) {
 $p->set_bookmark( 'list-start' );
 while ( $p->next_tag( array( 'tag_closers' => 'visit' ) ) ) {
 if ( 'UL' === $p->get_tag() && $p->is_tag_closer() ) {
 $p->set_bookmark( 'list-end' );
 $p->seek( 'list-start' );
 $p->set_attribute( 'data-contained-todos', (string) $total_todos );
 $total_todos = 0;
 $p->seek( 'list-end' );
 break;
 }

 if ( 'LI' === $p->get_tag() && ! $p->is_tag_closer() ) {
 $total_todos++;
 }
 }
}

Tokens and finer-grained processing.

It's possible to scan through every lexical token in the HTML document using the next_token() function. This alternative form takes no argument and provides no built-in query syntax.

Example:

 $title = '(untitled)';
 $text = '';
 while ( $processor->next_token() ) {
 switch ( $processor->get_token_name() ) {
 case '#text':
 $text .= $processor->get_modifiable_text();
 break;

 case 'BR':
 $text .= "\n";
 break;

 case 'TITLE':
 $title = $processor->get_modifiable_text();
 break;
 }
 }
 return trim( "# {$title}\n\n{$text}" );

Tokens and modifiable text.

Special "atomic" HTML elements.

Not all HTML elements are able to contain other elements inside of them.
For instance, the contents inside a TITLE element are plaintext (except that character references like & will be decoded). This means that if the string <img> appears inside a TITLE element, then it's not an image tag, but rather it's text describing an image tag. Likewise, the contents of a SCRIPT or STYLE element are handled entirely separately in a browser than the contents of other elements because they represent a different language than HTML.

For these elements the Tag Processor treats the entire sequence as one, from the opening tag, including its contents, through its closing tag.
This means that it's not possible to match the closing tag for a SCRIPT element unless it's unexpected; the Tag Processor already matched it when it found the opening tag.

The inner contents of these elements are that element's modifiable text.

The special elements are:

  • SCRIPT whose contents are treated as raw plaintext but supports a legacy style of including JavaScript inside of HTML comments to avoid accidentally closing the SCRIPT from inside a JavaScript string. E.g. console.log( '</script>' ).
  • TITLE and TEXTAREA whose contents are treated as plaintext and then any character references are decoded. E.g. 1 &lt; 2 < 3 becomes 1 < 2 < 3.
  • IFRAME, NOEMBED, NOFRAMES, STYLE, XMP whose contents are treated as raw plaintext and left as-is. E.g. 1 &lt; 2 < 3 remains 1 &lt; 2 < 3.

Other tokens with modifiable text.

There are also non-elements which are void/self-closing in nature and contain modifiable text that is part of that individual syntax token itself.

  • #text nodes, whose entire token is the modifiable text.
  • HTML comments and tokens that become comments due to some syntax error. The text for these tokens is the portion of the comment inside of the syntax.
    E.g. for <!-- comment --> the text is " comment " (note the spaces are included).
  • CDATA sections, whose text is the content inside of the section itself. E.g. for <![CDATA[some content]]> the text is "some content" (with restrictions [1]).
  • "Funky comments," which are a special case of invalid closing tags whose name is invalid. The text for these nodes is the text that a browser would transform into an HTML comment when parsing. E.g. for </%post_author> the text is %post_author.
  • DOCTYPE declarations like <DOCTYPE html> which have no closing tag.
  • Processing instruction nodes like <?wp __( "Like" ); ?> (with restrictions [2]).
  • The empty end tag </> which is ignored in the browser and DOM.

[1]: There are no CDATA sections in HTML. When encountering <![CDATA[, everything until the next > becomes a bogus HTML comment, meaning there can be no CDATA section in an HTML document containing >. The Tag Processor will first find all valid and bogus HTML comments, and then if the comment would have been a CDATA section were they to exist, it will indicate this as the type of comment.

[2]: HTML recognizes processing instructions whose target starts with an ASCII letter or _ and continues with ASCII alphanumerics, -, or _. The reserved xml and xml-stylesheet targets, as well as XML-valid targets with characters outside this set, transform into bogus comments in the DOM instead. Processing instructions exhibit the same constraint as CDATA sections, in that > cannot exist within the token since the processing instruction ends at the first >.

Design and limitations

The Tag Processor is designed to linearly scan HTML documents and tokenize HTML tags and their attributes. It's designed to do this as efficiently as possible without compromising parsing integrity. Therefore it will be slower than some methods of modifying HTML, such as those incorporating over-simplified PCRE patterns, but will not introduce the defects and failures that those methods bring in, which lead to broken page renders and often to security vulnerabilities. On the other hand, it will be faster than full-blown HTML parsers such as DOMDocument and use considerably less memory. It requires a negligible memory overhead, enough to consider it a zero-overhead system.

The performance characteristics are maintained by avoiding tree construction and semantic cleanups which are specified in HTML5. Because of this, for example, it's not possible for the Tag Processor to associate any given opening tag with its corresponding closing tag, or to return the inner markup inside an element. Systems may be built on top of the Tag Processor to do this, but the Tag Processor is and should be constrained so it can remain an efficient, low-level, and reliable HTML scanner.

The Tag Processor's design incorporates a "garbage-in-garbage-out" philosophy.
HTML5 specifies that certain invalid content be transformed into different forms for display, such as removing null bytes from an input document and replacing invalid characters with the Unicode replacement character U+FFFD (visually "�").
Where errors or transformations exist within the HTML5 specification, the Tag Processor leaves those invalid inputs untouched, passing them through to the final browser to handle. While this implies that certain operations will be non-spec-compliant, such as reading the value of an attribute with invalid content, it also preserves a simplicity and efficiency for handling those error cases.

Most operations within the Tag Processor are designed to minimize the difference between an input and output document for any given change. For example, the add_class and remove_class methods preserve whitespace and the class ordering within the class attribute; and when encountering tags with duplicated attributes, the Tag Processor will leave those invalid duplicate attributes where they are but update the proper attribute which the browser will read for parsing its value. An exception to this rule is that all attribute updates store their values as double-quoted strings, meaning that attributes on input with single-quoted or unquoted values will appear in the output with double-quotes.

Scripting Flag

The Tag Processor parses HTML with the "scripting flag" disabled. This means that it doesn't run any scripts while parsing the page. In a browser with JavaScript enabled, for example, the script can change the parse of the document as it loads. On the server, however, evaluating JavaScript is not only impractical, but also unwanted.

Practically this means that the Tag Processor will descend into NOSCRIPT elements and process its child tags. Were the scripting flag enabled, such as in a typical browser, the contents of NOSCRIPT are skipped entirely.

This allows the HTML API to process the content that will be presented in a browser when scripting is disabled, but it offers a different view of a page than most browser sessions will experience. E.g. the tags inside the NOSCRIPT disappear.

Text Encoding

The Tag Processor assumes that the input HTML document is encoded with a text encoding compatible with 7-bit ASCII's '<', '>', '&', ';', '/', '=', "'", '"', 'a' - 'z', 'A' - 'Z', and the whitespace characters ' ', tab, carriage-return, newline, and form-feed.

In practice, this includes almost every single-byte encoding as well as UTF-8. Notably, however, it does not include UTF-16. If providing input that's incompatible, then convert the encoding beforehand.

Compatibility

WordPress
since 6.5.0
  • 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).

Properties · 27

$htmlstringprotected
The HTML document to parse.
$last_queryarray|nullprivate
The last query passed to next_tag().
$sought_tag_namestring|nullprivate
The tag name this processor currently scans for.
$sought_class_namestring|nullprivate
The CSS class name this processor currently scans for.
$sought_match_offsetint|nullprivate
The match offset this processor currently scans for.
$stop_on_tag_closersboolprivate
Whether to visit tag closers, e.g. </div>, when walking an input document.
$parser_statestringprotected
Specifies mode of operation of the parser at any given time.
$compat_modestringprotected
Indicates if the document is in quirks mode or no-quirks mode.
$parsing_namespacestringprivate
Indicates whether the parser is inside foreign content, e.g. inside an SVG or MathML element.
$comment_typestring|nullprotected
What kind of syntax token became an HTML comment.
$text_node_classificationstringprotected
What kind of text the matched text node represents, if it was subdivided.
$bytes_already_parsedintprivate
How many bytes from the original HTML document have been read and parsed.
$token_starts_atint|nullprivate
Byte offset in input document where current token starts.
$token_lengthint|nullprivate
Byte length of current token.
$has_self_closing_flagboolprivate
Whether the current tag token has the self-closing flag.
$tag_name_starts_atint|nullprivate
Byte offset in input document where current tag name starts.
$tag_name_lengthint|nullprivate
Byte length of current tag name.
$text_starts_atintprivate
Byte offset into input document where current modifiable text starts.
$text_lengthintprivate
Byte length of modifiable text.
$is_closing_tagboolprivate
Whether the current tag is an opening tag, e.g. , or a closing tag, e.g. .
$attributesWP_HTML_Attribute_Token[]private
Lazily-built index of attributes found within an HTML tag, keyed by the attribute name.
$duplicate_attributes(WP_HTML_Span[])[]|nullprivate
Tracks spans of duplicate attributes on a given tag, used for removing all copies of an attribute when calling remove_attribute().
$classname_updatesarray<non-empty-string,private
Which class names to add or remove from a tag.
$bookmarksWP_HTML_Span[]protected
Tracks a semantic location in the original HTML which shifts with updates as they are applied to the document.
$lexical_updatesarray<int|string,protected
Lexical replacements to apply to input HTML document.
$seek_countintprotected
Tracks and limits seek() calls to prevent accidental infinite loops.
$skip_newline_atint|nullprivate
Whether the parser should skip over an immediately-following linefeed character, as is the case with LISTING, PRE, and TEXTAREA.

Methods · 51

Source code

class WP_HTML_Tag_Processor {	/**	 * The maximum number of bookmarks allowed to exist at	 * any given time.	 *	 * @since 6.2.0	 * @var int	 *	 * @see WP_HTML_Tag_Processor::set_bookmark()	 */	const MAX_BOOKMARKS = 10; 	/**	 * Maximum number of times seek() can be called.	 * Prevents accidental infinite loops.	 *	 * @since 6.2.0	 * @var int	 *	 * @see WP_HTML_Tag_Processor::seek()	 */	const MAX_SEEK_OPS = 1000; 	/**	 * The HTML document to parse.	 *	 * @since 6.2.0	 * @var string	 */	protected $html; 	/**	 * The last query passed to next_tag().	 *	 * @since 6.2.0	 * @var array|null	 */	private $last_query; 	/**	 * The tag name this processor currently scans for.	 *	 * @since 6.2.0	 * @var string|null	 */	private $sought_tag_name; 	/**	 * The CSS class name this processor currently scans for.	 *	 * @since 6.2.0	 * @var string|null	 */	private $sought_class_name; 	/**	 * The match offset this processor currently scans for.	 *	 * @since 6.2.0	 * @var int|null	 */	private $sought_match_offset; 	/**	 * Whether to visit tag closers, e.g. </div>, when walking an input document.	 *	 * @since 6.2.0	 * @var bool	 */	private $stop_on_tag_closers; 	/**	 * Specifies mode of operation of the parser at any given time.	 *	 * | State                    | Meaning                                                              |	 * |--------------------------|----------------------------------------------------------------------|	 * | *Ready*                  | The parser is ready to run.                                          |	 * | *Complete*               | There is nothing left to parse.                                      |	 * | *Incomplete*             | The HTML ended in the middle of a token; nothing more can be parsed. |	 * | *Matched tag*            | Found an HTML tag; it's possible to modify its attributes.           |

Changelog

Introduced in 6.2.0. 3 changes between 6.7.7 and 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.

7.1.0
Method get_decoded_attribute_value() added.verified against source
7.0.4
Method get_script_content_type() added.verified against source
7.0.4
Method escape_javascript_script_contents() added.verified against source
6.5.0
Pauses processor when input ends in an incomplete syntax token.
Introduces "special" elements which act like void elements, e.g. TITLE, STYLE.
Allows scanning through all tokens and processing modifiable text, where applicable.from the docblock
6.3.2
Fix: Skip HTML-like content inside rawtext elements such as STYLE.from the docblock
6.2.1
Fix: Support for various invalid comments; attribute updates are case-insensitive.from the docblock
6.2.0
Introduced.from the docblock

About this page

Parsed data
Generated from the wordpress-develop 7.1.0 tag, from src/wp-includes/html-api/class-wp-html-tag-processor.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.