我正在尝试编写一个函数,该函数将采用 RGB(A) 颜色并将其值保存在数组中,并提供排除 alpha 值的选项。我无法弄清楚如何编写与输入匹配的正则表达式,但我认为我正在寻找这样的东西:
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;
}
我希望能够为它提供任何有效形式的 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...
并让它产生一个数组:
[0] => '00', // red
[1] => '00', // green
[2] => '00', // blue
[3] => '1' // alpha only included if available and desired.
目前我可以通过 str_replace
完成此操作:
$color = 'rgb(12, 14, 85)';
$remove = array( 'rgb', 'a', '(', ')', ' ' );
$color = str_replace( $remove, '', $color );
$color = explode( ',', $color );
但感觉很老套,我找不到一个好方法来选择性地包含/排除 alpha。
感谢您的帮助,如果有与 preg_match
完全不同的方法会更好,我洗耳恭听。
最佳答案
我的答案不仅会提取您想要的子字符串值,还会执行相当高级别的验证(不是 100% 完美验证)。我修改了 https://stackoverflow.com/a/31245990/2943403 的模式更准确地服务于这个问题。我相信您会发现这个答案是准确、优雅和直接的。
如果你想剥离/简化模式,这会做:( Regex101 Demo )
~^rgba?\((\d+)\s*,\s*(\d+ )\s*,\s*(\d+)\s*(?:,\s*([.\d]+))?\)$~
代码:( Demo w/ $include_alpha = true ) ( Demo w/ $include_alpha = false ) ( Regex101 Demo )
function rgb_array($color, $include_alpha = true) {
$pattern = '~^rgba?\((25[0-5]|2[0-4]\d|1\d{2}|\d\d?)\s*,\s*(25[0-5]|2[0-4]\d|1\d{2}|\d\d?)\s*,\s*(25[0-5]|2[0-4]\d|1\d{2}|\d\d?)\s*(?:,\s*([01]\.?\d*?))?\)$~';
if (!preg_match($pattern, $color, $matches)) {
return []; // disqualified / no match
}
return array_slice($matches, 1, $include_alpha ? 4 : 3);
}
$strings = [
'rgb(0,0,0)',
'rgb(00,00,00)',
'rgb(0, 0, 0)',
'donkey eggs',
'rgb(00, 00, 00)',
'rgba(0,0,0,0.5)',
'rgba(255, 255, 255, 1)'
];
foreach ($strings as $string) {
echo "Process: $string\n";
var_export(rgb_array($string));
echo "\n";
}
输出:
Process: rgb(0,0,0)
array (
0 => '0',
1 => '0',
2 => '0',
)
Process: rgb(00,00,00)
array (
0 => '00',
1 => '00',
2 => '00',
)
Process: rgb(0, 0, 0)
array (
0 => '0',
1 => '0',
2 => '0',
)
Process: donkey eggs
array (
)
Process: rgb(00, 00, 00)
array (
0 => '00',
1 => '00',
2 => '00',
)
Process: rgba(0,0,0,0.5)
array (
0 => '0',
1 => '0',
2 => '0',
3 => '0.5',
)
Process: rgba(255, 255, 255, 1)
array (
0 => '255',
1 => '255',
2 => '255',
3 => '1',
)
附注如果您想使用 preg_split()
,您可以不那么具体地指定您的模式。这是给你的单线。 ( Demo )
function rgb_array($color, $include_alpha = true) {
return array_slice(preg_split('~[^\d.]+~', $color, -1, PREG_SPLIT_NO_EMPTY), 0, $include_alpha + 3);
}
关于php - 如何将 RGB(A) 值保存在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53136592/