views:

198

answers:

1

I'm writing a function that replaces long hex coded color (#334455) with short one (#345). This can be only done when each color in hex is multiple of 17 (each hex pair consists of the same characters).

e.g. #EEFFCC is replaced with #EFC, but #EDFFCC isn't replaced with anything.

I want to make this with single preg_replace() call without any custom callbacks.

I've already tried this:

$hex = preg_replace('/([0-f]){2}([0-f]){2}([0-f]){2}/i', '\1\2\3', $hex);

But that shortens all hexes, not just the hexes with same characters in each pair. I can't figure out how to match only pairs of same character.

Please help.

+4  A: 

Try this - you just need to use the backreferences in the match itself

$hex = preg_replace('/([0-f])\1([0-f])\2([0-f])\3/i', '\1\2\3', $hex);
Paul Dixon
Thanks, that works perfectly, I didn't know that backreferences can be used in patterns too. That brings a whole new dimension to regexps. :)
tomp