Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Converts Hex color values into rgba format.
- *
- * @param string $hex
- * @param mixed $alpha
- * @return string
- */
- function hexToRgb($hex, $alpha = 0)
- {
- // remove caret symbol from the start
- $hex = ltrim($hex, '#');
- // if short hex codes used, convert them to full length
- if (strlen($hex) === 3) {
- $hex = extendShortHex($hex);
- }
- validateHexColor($hex);
- // chunk hex value by two digits to get r, g and b values
- $hexArray = str_split($hex, 2);
- $hexArray = array_map(function ($item) {
- return hexdec($item);
- }, $hexArray);
- $hexArray['alpha'] = (float)$alpha;
- return "rgb($hexArray[0], $hexArray[1], $hexArray[2], $hexArray[alpha])";
- }
- /**
- * Validates hex color values by length and the digits.
- *
- * @param string $hex
- * @throws Error
- */
- function validateHexColor($hex)
- {
- // hex length validation
- if (strlen($hex) !== 6) {
- throw new Error('Hex code must be 6 digits long.');
- }
- // hex digit validation
- if (ctype_xdigit($hex) === false) {
- throw new Error('Please provide a valid hex number.');
- }
- }
- /**
- * Short hex codes are converted into six digits.
- *
- * @param string $hex
- * @return string
- */
- function extendShortHex($hex)
- {
- return $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement