You are here

public static function TwigColor::hexToRgb in Twig Tools 8

Returns an array of equivalent RGB values of the passed hexadecimal color.

Parameters

string $hex: The hexadecimal color to get the RGB equivalent colors values of.

Return value

array The array of equivalent equivalent RGB color values.

1 call to TwigColor::hexToRgb()
TwigColor::hexToCssRgb in src/TwigExtension/TwigColor.php
Returns the CSS RGB string equivalent of the passed hexadecimal color.

File

src/TwigExtension/TwigColor.php, line 96

Class

TwigColor
Class TwigConvert.

Namespace

Drupal\twig_tools\TwigExtension

Code

public static function hexToRgb($hex) {

  // Regex pattern validating hexadecimal colors.
  $pattern = '/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/';
  preg_match($pattern, $hex, $match);
  if (isset($match[1])) {
    $hex_string = $match[1];

    // Check for shorthand hexadecimal color format.
    if (strlen($hex_string) === 3) {
      $char_array = str_split($hex_string, 1);
      $hex_color = '';

      // Double each character to convert the string to a 6-character
      // hexadecimal color.
      foreach ($char_array as $char) {
        $hex_color = $hex_color . $char . $char;
      }
    }
    else {
      $hex_color = $hex_string;
    }

    // Convert the hexadecimal color string to an array of hexadecimal
    // RGB values.
    $rgb = str_split($hex_color, 2);

    // Convert the array of hexadecimal RGB values to an array of integer
    // RGB values.
    $rgb = array_map('hexdec', $rgb);
    return $rgb;
  }
}