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". 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.
// 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];
You can access characters of a string as an array.
this question cannot miss the good old regexes :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
<?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...
精彩评论