<?php
function normalizeHexColor(string $color): ?string {
$hex = ltrim(trim($color), '#');
if (!preg_match('/^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i', $hex)) {
return null;
}
$hex = strtolower($hex);
// Expand 3/4-digit shorthand to 6/8-digit.
if (in_array(strlen($hex), [3, 4], true)) {
$expanded = '';
foreach (str_split($hex) as $c) $expanded .= $c . $c;
$hex = $expanded;
}
return '#' . $hex;
}
echo normalizeHexColor('#fff'); // #ffffff
echo normalizeHexColor('00aaffcc'); // #00aaffcc
var_dump(normalizeHexColor('xyz')); // null
Create a free account and build your private vault. Share publicly whenever you want.