Question

I want to convert my hex color from a color input (example: #FFFFFF) to a PHP hex number format (example: 0xFFFFFF).

i tried to replace the # with 0x by using str_replace but this converted it to a string, I want to keep it a number.

Any solution?

Was it helpful?

Solution

Perhaps this function is what you need?

http://www.php.net/manual/en/function.hexdec.php

"Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number.

hexdec() will ignore any non-hexadecimal characters it encounters."

Some added info:

dechex() will give you a string containing a hex representation of the number if you need it, but it seems you should be dealing with an integer if it's a number that you need to pass around.

OTHER TIPS

Can you try this, Found a function here

        function hex2rgb($hex) {
            $hex = str_replace("#", "", $hex);

            if(strlen($hex) == 3) {
                $r = hexdec(substr($hex,0,1).substr($hex,0,1));
                $g = hexdec(substr($hex,1,1).substr($hex,1,1));
                $b = hexdec(substr($hex,2,1).substr($hex,2,1));
            } else {
                $r = hexdec(substr($hex,0,2));
                $g = hexdec(substr($hex,2,2));
                $b = hexdec(substr($hex,4,2));
            }
            $rgb = array($r, $g, $b);
            return implode("", $rgb); // returns the rgb values separated by commas
            //return $rgb; // returns an array with the rgb values
        }
        echo $rgb = hex2rgb("#cc0");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top