wp-includes/html-api/class-wp-html-tag-processor.php:411Core class used to modify attributes in an HTML document for tags matching a query.
<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. <h3>Bookmarks</h3> 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++;
}
}
} <h2>Tokens and finer-grained processing.</h2> 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}" ); <h3>Tokens and <em>modifiable text</em>.</h3> <h4>Special "atomic" HTML elements.</h4> 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 <em>modifiable text</em>. The special elements are: <ul> <li>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>' ).</li> <li>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.</li> <li>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.</li> </ul> <h4>Other tokens with modifiable text.</h4> 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. <ul> <li>#text nodes, whose entire token <em>is</em> the modifiable text.</li> <li>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).</li> <li>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]).</li> <li>"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.</li> <li>DOCTYPE declarations like <DOCTYPE html> which have no closing tag.</li> <li>Processing instruction nodes like <?wp __( "Like" ); ?> (with restrictions [2]).</li> <li>The empty end tag </> which is ignored in the browser and DOM.</li> </ul> [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 <em>would</em> have been a CDATA section <em>were they to exist</em>, 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 >. <h2>Design and limitations</h2> 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. <h3>Scripting Flag</h3> 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. <h3>Text Encoding</h3> 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.$htmlstringprotected$last_queryarray|nullprivate$sought_tag_namestring|nullprivate$sought_class_namestring|nullprivate$sought_match_offsetint|nullprivate$stop_on_tag_closersboolprivate$parser_statestringprotected$compat_modestringprotected$parsing_namespacestringprivate$comment_typestring|nullprotected$text_node_classificationstringprotected$bytes_already_parsedintprivate$token_starts_atint|nullprivate$token_lengthint|nullprivate$has_self_closing_flagboolprivate$tag_name_starts_atint|nullprivate$tag_name_lengthint|nullprivate$text_starts_atintprivate$text_lengthintprivate$is_closing_tagboolprivate$attributesWP_HTML_Attribute_Token[]private$duplicate_attributes(WP_HTML_Span[])[]|nullprivateremove_attribute().$classname_updatesarray<non-empty-string,private$bookmarksWP_HTML_Span[]protected$lexical_updatesarray<int|string,protected$seek_countintprotectedseek() calls to prevent accidental infinite loops.$skip_newline_atint|nullprivateclass 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. |Introduced in 6.2.0. 3 changes between 6.7.7 and 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
get_decoded_attribute_value() added.verified against sourceget_script_content_type() added.verified against sourceescape_javascript_script_contents() added.verified against sourcesrc/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.