WP_HTML_Tag_Processor::get_attribute_names_with_prefix │ public │ WP 6.2.0

Gets lowercase names of all attributes matching a given prefix in the current tag.

Note that matching is case-insensitive. This is in accordance with the spec:

There must never be two or more attributes on > the same start tag whose names are an ASCII > case-insensitive match for each other.

- HTML 5 spec

Example:

$p = new WP_HTML_Tag_Processor( '<div data-ENABLED class="test" DATA-test-id="14">Test</div>' );
$p->next_tag( array( 'class_name' => 'test' ) ) === true;
$p->get_attribute_names_with_prefix( 'data-' ) === array( 'data-enabled', 'data-test-id' );
$p->next_tag() === false;
$p->get_attribute_names_with_prefix( 'data-' ) === null;

Method of the class: WP_HTML_Tag_Processor{}

No Hooks.

Returns

array|null. List of attribute names, or null when no tag opener is matched.

Usage

$WP_HTML_Tag_Processor = new WP_HTML_Tag_Processor();
$WP_HTML_Tag_Processor->get_attribute_names_with_prefix( $prefix ): ?array;
$prefix(string) (required)
Prefix of requested attribute names.

Notes

See: https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive

Changelog

Since 6.2.0 Introduced.

WP_HTML_Tag_Processor::get_attribute_names_with_prefix() code WP 7.1.4

public function get_attribute_names_with_prefix( $prefix ): ?array {
	if (
		self::STATE_MATCHED_TAG !== $this->parser_state ||
		$this->is_closing_tag
	) {
		return null;
	}

	$comparable = strtolower( $prefix );

	/*
	 * For the `class` attribute, ensure that enqueued class changes from
	 * `add_class` and `remove_class` are flushed into attribute updates.
	 */
	$has_class = isset( $this->attributes['class'] );
	if ( '' === $comparable || str_starts_with( 'class', $comparable ) ) {
		foreach ( $this->classname_updates as $update ) {
			if (
				( $has_class && self::REMOVE_CLASS === $update ) ||
				( ! $has_class && self::ADD_CLASS === $update )
			) {
				$this->class_name_updates_to_attributes_updates();
				break;
			}
		}
	}

	$additions = array();
	$removals  = array();
	foreach ( $this->lexical_updates as $update_name => $update ) {
		if ( is_int( $update_name ) || 'modifiable text' === $update_name ) {
			continue;
		}

		if ( '' === $update->text ) {
			$removals[ $update_name ] = true;
		} elseif ( ! isset( $this->attributes[ $update_name ] ) && str_starts_with( $update_name, $comparable ) ) {
			$additions[] = $update_name;
		}
	}

	$matches = array();
	foreach ( array_keys( $this->attributes ) as $attr_name ) {
		if ( str_starts_with( $attr_name, $comparable ) && ! isset( $removals[ $attr_name ] ) ) {
			$matches[] = $attr_name;
		}
	}

	return empty( $additions ) ? $matches : array_merge( $additions, $matches );
}