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
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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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