0

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?

4
  • You can use the number() function of PHP to convert your string into a number. Commented Jan 29, 2014 at 16:40
  • hexdec() & dechex() Commented Jan 29, 2014 at 16:43
  • @LajosArpad what number() !!? Commented Jan 29, 2014 at 16:54
  • This here will do all sorts of conversions. Commented Mar 22, 2019 at 14:24

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

my question is simple: i want to convert css color representation in hex (for example #FFFFFF) to PHP hex number (for example 0x000000).
@RafikHaceb I added some context to my answer.
1

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");

4 Comments

@BeatAlex. Thanks for pointing out, there is an option for both array and number aswell!
I somehow deleted my comment, was an accident. But I didn't look into it and if there's a number then I apologies!
@BeatAlex, No issues!
I didn't ask for RGB representation , i want to convert a css color representation in hex to php hex number: #FFFFFF to 0xFFFFFF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.