Jump to content

Shortening six-digit hex color code


127.0.0.1

Recommended Posts

This question is regarding the use of regex to shorten six-digit hex color codes to its three-digit counterpart.

[url=http://www.w3.org/TR/REC-CSS2/syndata.html#color-units]The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display. [/url]

The problem I'm having is very simple; using regex to determine if the [u]same instance[/u] of a word character has repeated itself once. For example detecting [tt]ff[/tt] and not [tt]fe[/tt] or [tt]f0[/tt] et cetera.

I don't know how to make regex identify if the same character has repeated itself.
Link to comment
https://forums.phpfreaks.com/topic/35751-shortening-six-digit-hex-color-code/
Share on other sites

Each pair of parentheses creates a backreference; the first is \1, the second \2, and so on.

[code]
<pre>
<?php
$tests = array(
'#ffffff',
'#FFFFFF',
'#fefefe',
'#FFFEFF',
'#ffbb00',
'#FFBB00',
'#abcdef',
);
$hex_char = '[a-f0-9]';
foreach ($tests as $test) {
echo $test, ' => ';
$test = preg_replace("/(?<=^#)($hex_char)\\1($hex_char)\\2($hex_char)\\3\z/i", '\1\2\3', $test);
echo $test, '<br>';
}
?>
</pre>

[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.