How to convert RGBA color codes to 8 Digit Hex in PHP?

CRA*_*AIG 1 php colors subtitle rgba

I'm attempting to convert some rgba values into a format suitable for SubStation Alpha subtitle files. The .ass file format requires a colour format like &H12345690 where the hex bytes are in blue, green, red, alpha order.

I am finding examples converting 8 digit hex colors into RGBA, but not the other way around. Here is a function I put together based one of the answers, but the alpha channel is always returned as zero:

function rgbtohex($string) {
    $string = str_replace("rgba","",$string);
    $string = str_replace("rgb","",$string);
    $string = str_replace("(","",$string);
    $string = str_replace(")","",$string);
    $colorexplode = explode(",",$string);    
    $hex = '&H';
    
    foreach($colorexplode AS $c) {
        echo "C" . $c . " " . dechex($c) . "<br><br>";
        $hex .= dechex($c);      
    }
    return $hex;
}
Run Code Online (Sandbox Code Playgroud)

But if I test it with rgba(123,223,215,.9) it produces &H7bdfd70 which only has 7 characters instead of 8.

Also, the alpha channel (.9) always comes out to zero, so that doesn't appear to be working correctly.

mik*_*n32 6

您可以使用该printf()函数系列来转换为正确填充的十六进制字符串。小数不能用十六进制表示,因此该值被视为 0xFF 的分数。

$rgba = "rgba(123,100,23,.5)";

// get the values
preg_match_all("/([\\d.]+)/", $rgba, $matches);

// output
$hex = sprintf(
    "&H%02X%02X%02X%02X",
    $matches[1][2], // blue
    $matches[1][1], // green
    $matches[1][0], // red
    $matches[1][3] * 255, // adjusted opacity
);
echo $hex;
Run Code Online (Sandbox Code Playgroud)

输出:

&H17647B7F
Run Code Online (Sandbox Code Playgroud)