I'm trying to write a function that will take an RGB(A) color and save its values in an array, with an option to exclude the alpha value. I'm having trouble figuring out how to write the regex that will match the input, but I'm thinking that something like this is what I'm looking for:
function rgb_array( $color, $include_alpha = true ) {
$pattern = 'what goes here?';
$color = preg_match( $pattern, $color, $matches);
if ( $include_alpha == true && ! empty( $matches[4] ) ) {
$color = array( $matches[1], $matches[2], $matches[3], $matches[4] );
} else {
$color = array( $matches[1], $matches[2], $matches[3] );
}
return $color;
}
I would like to be able to feed it any valid form of rgb/rgba:
rgb(0,0,0)
rgb(00,00,00)
rgb(0, 0, 0)
rgb(00, 00, 00)
rgba(0,0,0,0.5)
rgba(255, 255, 255, 1)
etc...
And have it produce an array:
[0] => '00', // red
[1] => '00', // green
[2] => '00', // blue
[3] => '1' // alpha only included if available and desired.
At the moment I'm able to accomplish this through str_replace
:
$color = 'rgb(12, 14, 85)';
$remove = array( 'rgb', 'a', '(', ')', ' ' );
$color = str_replace( $remove, '', $color );
$color = explode( ',', $color );
But it feels hacky and I can't find a good way to optionally include/exclude alpha.
Thanks for your help, and if there's a completely different approach than preg_match
that would be better, I'm all ears.