[英]Convert an hexadecimal number to a string
我正在嘗試將十六進制數轉換為正確的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>';
}
為什么不簡單地使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.