PHP

Validate Hex Color

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Accept #RGB, #RGBA, #RRGGBB, or #RRGGBBAA hex colors (with or without the leading #). Returns the normalized 6/8-digit lowercase form.
PHP
Raw
<?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
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.