Jump to content

[SOLVED] String losing zero's


MasterACE14

Recommended Posts

This is a small part of my script which isn't working 100% right.

<?php
function HexToRGB($hex) {
	$hex = ereg_replace("#", "", $hex);
	$color = array();

	if(strlen($hex) == 3) {
		$color['r'] = hexdec(substr($hex, 0, 1) . $r);
		$color['g'] = hexdec(substr($hex, 1, 1) . $g);
		$color['b'] = hexdec(substr($hex, 2, 1) . $b);
	}
	else if(strlen($hex) == 6) {
		$color['r'] = hexdec(substr($hex, 0, 2));
		$color['g'] = hexdec(substr($hex, 2, 2));
		$color['b'] = hexdec(substr($hex, 4, 2));
	}

	return $color;
}

if(isset($_GET['tc'])) {
if(strlen($_GET['tc']) == 6) {
$TextColor = HexToRGB($_GET['tc']);
$TextColor = ImageColorAllocate($img, $TextColor['r'], $TextColor['g'], $TextColor['b']);
}
}
?>

 

if $_GET['tc'] is equal to something ending with a zero like the Hexadecimal for Red for example FF0000 , then it appears to be losing the last 4 zero's, the hexadecimal only appears to be working when $_GET['tc'] doesn't end with a zero. For example FF000F will work fine cause it ends with F not zero.

 

How come I am losing zero's ?

 

Regards, ACE

Link to comment
https://forums.phpfreaks.com/topic/153715-solved-string-losing-zeros/
Share on other sites

try this instead:

<?php 
  function HexToRGB($hex) {
      $hex = ereg_replace("#", "", $hex);
      $color = array();

      if(strlen($hex) == 3) {
         $color['r'] = (string)hexdec(substr($hex, 0, 1) . $r);
         $color['g'] = (string)hexdec(substr($hex, 1, 1) . $g);
         $color['b'] = (string)hexdec(substr($hex, 2, 1) . $b);
      }
      else if(strlen($hex) == 6) {
         $color['r'] = (string)hexdec(substr($hex, 0, 2));
         $color['g'] = (string)hexdec(substr($hex, 2, 2));
         $color['b'] = (string)hexdec(substr($hex, 4, 2));
      }

      return $color;
   }
?>

 

I'm guessing PHP is going "mmmh a 0 is an int.. 0 = no value".

Alternatively, use the function from here: http://www.jonasjohn.de/snippets/php/hex2rgb.htm

For these kind of 'somewhat common' things you can pretty much bet there's always someone else who already wrote it before you did... at the very least used his idea of:

$hex = str_replace("#", "", $hex);

 

Always use the PHP default string manipulation functions instead of a regex whenever possible, they're many times faster.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.