tags:

views:

182

answers:

4

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.

+7  A: 

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
}
Ben S
+1 - visual documentation.
mynameiscoffey
Fantastic! I didn't know you could grab a character of a string with $variable[lenght]; I've learned a lot from this. Thank you!
Chad Whitaker
+4  A: 

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

You can access characters of a string as an array.

Macmade
+1  A: 

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 …

knittl
This is hardly efficient in processing or legibility. I say avoid regexes when a simpler solution will suffice :P
Ben S
i didn't say that ;) it's just provided so all regex-users are happy
knittl
A: 

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...

Marcx
Certainly not the most efficient, because of the str_split call and the foreach loop. But that will work too...
Macmade