Verifying color code

<?php
$myColor="0000ff";
?>

I have a variable named $myColor like the above.

I like to verify whether the value of $myColor is color code or not.

The following code doesn’t work correctly, but I hope it shows what I want.

[b]code1[/b]

<?php
$myColor="0000ff";

if ( is_colorCode($myColor) )
{echo yes;}
else
{ echo no;}
?>

[b]result1[/b]

yes
[b]code2[/b]

<?php
$myColor="0[COLOR="#FF0000"]xy[/COLOR]0000";

if ( is_colorCode($myColor) )
{echo yes;}
else
{ echo no;}
?>

[b]result2[/b]

no

you can use a regex to see if $myColor contains only 0-9 and/or a-f charachters

/[1]{6}$/i


  1. 0-9a-f ↩︎

I am afraid that the code below which is one of my trials applying your code doesn’t work correctly.

 if ( $myColor contains [COLOR="#FF0000"]/^[0-9a-f]{6}$/i[/COLOR] )
{echo yes;}
else
{echo no;}

  1. 0-9a-f ↩︎

That’s not PHP. There is no ‘contains’ in PHP.


<?php

$myColor="0000ff";

if(preg_match('/^[0-9a-f]{6}$/i', $myColor)) {
    echo "Match";
} else {
    echo "No match";
}

?>

Isn’t a 3 digit Hex representation of a colour also valid?


$string = '000fff';
$len = strlen($string);

    if (ctype_xdigit($string) && ($len == 3 || $len == 6) ) 
        echo "The string $string is a valid color";

Very nice Cups, here’s how the Imagine library validates an incoming colour declaration.

[URL=“https://github.com/avalanche123/Imagine/blob/develop/lib/Imagine/Image/Color.php#L176”]https://github.com/avalanche123/Imagine/blob/develop/lib/Imagine/Image/Color.php#L176

Truth be told, I guess it only really ensures the value supplied can be transformed into a colour, rather than validating the value.

Thank you to All.

A 3 digit length is also valid, yes.
Cups, your version would allow stuff like… #ayh9ep, right? Which isn’t valid. The Imagine library doesn’t check that either.

Right… /[1]{3,6}$/i’ … No, that’ll allow 4 and 5 character colour codes too. And there my regex skillz fail. :slight_smile:


  1. 0-9a-f ↩︎

“ayh9ep” fails the ctype_xdigit() test for me? (Win32, 5.2.6) as does “#ayh9ep”?

Ah, my bad! I hadn’t noticed the ‘x’ in ctype_xdigit.

My apologies, good sir. :slight_smile: