WP_HTML_Tag_Processor::class_list()publicWP 6.4.0

Generator for a foreach loop to step through each class name for the matched tag.

This generator function is designed to be used inside a "foreach" loop.

Example:

$p = new WP_HTML_Tag_Processor( "<div class='free <egg<\tlang-en'>" );
$p->next_tag();
foreach ( $p->class_list() as $class_name ) {
	echo "{$class_name} ";
}
// Outputs: "free <egg> lang-en "

Method of the class: WP_HTML_Tag_Processor{}

No Hooks.

Return

null. Nothing (null).

Usage

$WP_HTML_Tag_Processor = new WP_HTML_Tag_Processor();
$WP_HTML_Tag_Processor->class_list();

Changelog

Since 6.4.0 Introduced.

WP_HTML_Tag_Processor::class_list() code WP 6.6.2

public function class_list() {
	if ( self::STATE_MATCHED_TAG !== $this->parser_state ) {
		return;
	}

	/** @var string $class contains the string value of the class attribute, with character references decoded. */
	$class = $this->get_attribute( 'class' );

	if ( ! is_string( $class ) ) {
		return;
	}

	$seen = array();

	$at = 0;
	while ( $at < strlen( $class ) ) {
		// Skip past any initial boundary characters.
		$at += strspn( $class, " \t\f\r\n", $at );
		if ( $at >= strlen( $class ) ) {
			return;
		}

		// Find the byte length until the next boundary.
		$length = strcspn( $class, " \t\f\r\n", $at );
		if ( 0 === $length ) {
			return;
		}

		/*
		 * CSS class names are case-insensitive in the ASCII range.
		 *
		 * @see https://www.w3.org/TR/CSS2/syndata.html#x1
		 */
		$name = strtolower( substr( $class, $at, $length ) );
		$at  += $length;

		/*
		 * It's expected that the number of class names for a given tag is relatively small.
		 * Given this, it is probably faster overall to scan an array for a value rather
		 * than to use the class name as a key and check if it's a key of $seen.
		 */
		if ( in_array( $name, $seen, true ) ) {
			continue;
		}

		$seen[] = $name;
		yield $name;
	}
}