【问题标题】:Convert an hexadecimal number to a string将十六进制数转换为字符串
【发布时间】:2013-11-23 06:04:36
【问题描述】:

我正在尝试将十六进制数字转换为正确的css 格式:

$white = hexdec('#ffffff');

//Loops for a bunch of colours
for( $i = 0 ; $i <= $white ; $i=$i+5000 ) 
{
    //set default css background-color property
    $backgroundValue = dechex( $i );

    //if there are less of 7 characters (ex. #fa444, or #32F, ...)  
    if( $numLen = strlen( dechex( $i )) < 7 ) 
    {
        //insert (7 - numbers of characters) number of zeros after # 
        for ( $j = 0 ; $j < 7 - $numLen ; $j++ )
            $backgroundValue = strtr( $backgroundValue, '#', '#0' );                
    }
    //echo each div with each background-color property. 
    echo '<div class="colour" style="width: 10%; float: left; background: '.$backgroundValue.';">'.dechex($i).'</div>';
}

但这不起作用。我怎么能把十六进制数变成一个字符串,比如:#FFFFFF。

更新:

问题是我没有将# 传递到字符串的开头:$backgroundValue = '#'.dechex( $i );。

这段代码运行良好:

        $white = hexdec('#ffffff');
        for( $i = 0 ; $i <= $white ; $i=$i+10000 ) 
        {
            $backgroundValue = '#'.dechex( $i );
            $numLen = strlen( dechex( $i ));

            if( $numLen < 6 ) 
            {

                for ( $j = 0 ; $j < (6 - $numLen) ; $j++ )
                    $backgroundValue = str_replace( '#', '#0', $backgroundValue );              
            }

            echo '<div class="colour" style="width: 10%; float: left; background: '.$backgroundValue.';">'.$backgroundValue.'</div>';
        } 

【问题讨论】:

标签: php string hex


【解决方案1】:

为什么不直接使用str_repeat?

$end = 0xffffff;

for ($i = 0; $i < $end; $i += 5000) {
    $color = (string) dechex($i);
    $backgroundValue = '#' . str_repeat('0', 6 - strlen($color)) . $color;
    echo '<div class="colour" style="width: 10%; float: left; background: '.$backgroundValue.';">'.dechex($i).'</div>';
}

你也可以使用 sprintf

$backgroundValue = sprintf('#%06x', $i);

【讨论】:

  • 既然有str_pad功能,为什么还要使用str_repeat? '#'.str_pad(dechex($i), 6, '0', STR_PAD_LEFT)
  • 注意:您的 str_repeat 错误! ffff00 = 16776960, 00ffff or ffff = 65535
  • $backgroundValue 不正确。请更改为:$backgroundValue = '#' . str_repeat('0', 6 - strlen($color)) . $color;
  • 对不起 - 我弄错了。用sprintf添加了一个更短的版本@
猜你喜欢
  • 2018-01-31
  • 2018-01-22
  • 1970-01-01
  • 2013-02-07
  • 2014-03-19
  • 2015-11-29
  • 1970-01-01
相关资源
最近更新 更多