var_dump(isValidHexCode("#CD5C5C")); // ➞ true
var_dump(isValidHexCode("#EAECEE")); // ➞ true
var_dump(isValidHexCode("#eaecee")); // ➞ true
var_dump(isValidHexCode("#CD5C58C")); // ➞ false
// Length exceeds 6
var_dump(isValidHexCode("#CD5C5Z")); // ➞ false
// Not all alphabetic characters in A-F
var_dump(isValidHexCode("#CD5C&C")); // ➞ false
// Contains unacceptable character
var_dump(isValidHexCode("CD5C5C")); // ➞ false
// Missing #
function isValidHexCode($code) {
$allowed = '0123456789abcdef';
$len = strlen($code);
if ($len!=7 || $code[0]!='#') {
return false;
}
for ($i=1; $i<$len; $i++) {
if (!str_contains($allowed, strtolower($code[$i]))) {
return false;
}
}
return true;
}