dotJoon
October 23, 2011, 12:02am
1
<?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
system
October 23, 2011, 12:49am
2
you can use a regex to see if $myColor contains only 0-9 and/or a-f charachters
felgall:
/{6}$/i
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;}
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?
Cups
October 23, 2011, 12:17pm
7
$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.
Immerse
October 24, 2011, 6:56am
10
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… /{3,6}$/i’ … No, that’ll allow 4 and 5 character colour codes too. And there my regex skillz fail.
Cups
October 24, 2011, 9:15am
11
“ayh9ep” fails the ctype_xdigit() test for me? (Win32, 5.2.6) as does “#ayh9ep ”?
Immerse
October 25, 2011, 6:05am
12
Ah, my bad! I hadn’t noticed the ‘x’ in ctype_xdigit.
My apologies, good sir.