W3cubDocs

/WordPress

WP_Duotone::colord_parse_hex( string $hex ): array|null

Parses any valid Hex3, Hex4, Hex6 or Hex8 string and converts it to an RGBA object.

Description

Direct port of colord’s parseHex function.

Parameters

$hexstringrequired
The hex string to parse.

Return

array|null An array of RGBA values or null if the hex string is invalid.

Source

private static function colord_parse_hex( $hex ) {
	$is_match = preg_match(
		'/^#([0-9a-f]{3,8})$/i',
		$hex,
		$hex_match
	);

	if ( ! $is_match ) {
		return null;
	}

	$hex = $hex_match[1];

	if ( 4 >= strlen( $hex ) ) {
		return array(
			'r' => (int) base_convert( $hex[0] . $hex[0], 16, 10 ),
			'g' => (int) base_convert( $hex[1] . $hex[1], 16, 10 ),
			'b' => (int) base_convert( $hex[2] . $hex[2], 16, 10 ),
			'a' => 4 === strlen( $hex ) ? round( base_convert( $hex[3] . $hex[3], 16, 10 ) / 255, 2 ) : 1,
		);
	}

	if ( 6 === strlen( $hex ) || 8 === strlen( $hex ) ) {
		return array(
			'r' => (int) base_convert( substr( $hex, 0, 2 ), 16, 10 ),
			'g' => (int) base_convert( substr( $hex, 2, 2 ), 16, 10 ),
			'b' => (int) base_convert( substr( $hex, 4, 2 ), 16, 10 ),
			'a' => 8 === strlen( $hex ) ? round( (int) base_convert( substr( $hex, 6, 2 ), 16, 10 ) / 255, 2 ) : 1,
		);
	}

	return null;
}

Changelog

Version Description
6.3.0 Introduced.

© 2003–2024 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/classes/wp_duotone/colord_parse_hex