It may be easier:
function validate_color($str){ return (($l=strlen($str))==3)||($l==6)) && sscanf($str,"%x", $color); } print(validate_color("AAA")? "цвет валидный": "цвет не валидный");
PS We remove questions on speed:
function validate_color_sscan($str){ return ($l=strlen($str)) && (($l==3)||($l==6)) && sscanf($str,"%x", $color); } function test_sscan($str){ for($i=0; $i<2000000; $i++) $v=($l=strlen($str)) && (($l==3)||($l==6)) && sscanf($str,"%x", $color); } function validate_color_preg($str){ return preg_match('/^[A-F0-9]{3}([A-F0-9]{3})?$/i', $str); } function test_preg($str){ for($i=0; $i<2000000; $i++) $v=preg_match('/[a-f0-9]{3}([a-f0-9]{3})?$/i', $str); } print(validate_color_sscan("AAA")? "<br>цвет валидный": "<br>цвет не валидный"); print(validate_color_preg("AAA")? "<br>цвет валидный": "<br>цвет не валидный"); $time0 = microtime(true); test_sscan($str); $time1 = microtime(true); test_preg($str); $time2 = microtime(true); printf("<br>test_sscan x 2000000: %d mcs", $time1-$time0); printf("<br>test_preg x 2000000: %d mcs", $time2-$time1);
Results:
color is valid
color is valid
test_sscan x 2000000: 8 mcs
test_preg x 2000000: 14 mcs
ffff
in questionffff
not a valid color value in HTML — it must be either 3 or 6 hexadecimal digits. - Sergiksrgb(255,128,0)
do not consider? - Sergiks