This PHP script checks if a string $color is a hex color or not. The second IF statement will add the pound symbol at the beginning if it is missing from the hex color value.
//Check for a hex color string '#c1c2b4'
if(preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid
{
//Verified hex color
}
//Check for a hex color string without hash 'c1c2b4'
elseif(preg_match('/^[a-f0-9]{6}$/i', $color)) //hex color is valid
{
$fix_color = '#' . $color;
}
Source:
http://code.hyperspatial.com/250/verify-hex-color-string/
