简体   繁体   English

PHP:将速记十六进制颜色转换为常规

[英]PHP: Convert shorthand Hex Colors to Regular

I'm trying to make a function that will take short hand hex color to the long hex color. 我正在尝试制作将短手部十六进制颜色变为长方十六进制颜色的函数。

For example if someone submits "f60" it will convert to "ff6600". 例如,如果有人提交“ f60”,它将转换为“ ff6600”。 I understand I need to repeat each number as itself, but what is the most efficient way to do this? 我知道我需要重复每个数字本身,但是最有效的方法是什么?

Thank you. 谢谢。

This should work. 这应该工作。 However, you'll want to make sure the strings aren't prepended with a # due to the exact strlen comparison. 但是,你要确保字符串不带前缀#由于确切strlen比较。

// Done backwards to avoid destructive overwriting
// Example: f60 -> ff6600
if (strlen($color) == 3) {
    $color[5] = $color[2]; // f60##0
    $color[4] = $color[2]; // f60#00
    $color[3] = $color[1]; // f60600
    $color[2] = $color[1]; // f66600
    $color[1] = $color[0]; // ff6600
}

$fullColor = $color[0].$color[0].$color[1].$color[1].$color[2].$color[2];

您可以将字符串的字符作为数组访问。

this question cannot miss the good old regexes :D 这个问题不能错过好的旧正则表达式:D

 $color = preg_replace('/#([\da-f])([\da-f])([\da-f])/i', '#\1\1\2\2\3\3', $color);

not the best solution though … 虽然不是最好的解决方案……

Not the most efficient, but an alternative with these you can duplicate every kind of string with every length not only 3 as Hex colors 这不是最有效的方法,但是您可以用这些方法的另一种方法来复制每种长度不只有3种十六进制颜色的字符串

   <?php
     $double='';
     for($i=0;$i<strlen($str);$i++){
            $double.=$str[$i].$str[$i];
     }
   ?>

or 要么

<?php
 $str="FCD";
 $split=str_split($str);
 $str='';
 foreach($split as $char) $str.=$char.$char;
 echo $str;
?>

You could also use regex or other... 您还可以使用正则表达式或其他...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM