Page 1 of 1
is preg_replace the right way to do this?
Posted: Wed Nov 24, 2010 12:04 pm
by someguyhere
Currently, I'm using str_replace with an array hard coded to replace css colors to the shortened versions. For example, it changes #FFFFFF to #FFF, but it gets pretty cumbersome adding more colors to the array.
I would imagine there is a better way to do this using preg_replace, but I have no idea where to look. Am I right, and if so, how would I go about this?
Re: is preg_replace the right way to do this?
Posted: Wed Nov 24, 2010 12:42 pm
by s992
Are you just truncating the last three characters regardless of what they are, or is it more complex than that?
Re: is preg_replace the right way to do this?
Posted: Wed Nov 24, 2010 12:48 pm
by someguyhere
More complicated, but I think only slightly.
It will be cases where it's six of the same characters, so it could be CCCCCC, FFFFFF, 000000, etc. Ideally, I would like for it to be case insensitive, so that either FFFFFF or ffffff would be converted to fff.
Re: is preg_replace the right way to do this?
Posted: Wed Nov 24, 2010 1:10 pm
by McInfo
See if you can expand this example to get what you need.
Code: Select all
print_r(preg_replace('/^([0-9])\1$/i', '\1', array('22', '53', '77', '61')));
/*
Output Array
(
[0] => 2
[1] => 53
[2] => 7
[3] => 61
)
*/
- / / regex bounds
- ^ start of string
- ( ) bounds of a subpattern
- [ ] bounds of a character class
- 0-9 range of characters 0-9
- \1 reference to the first subpattern
- $ end of string
- i case-insensitivity modifier
Re: is preg_replace the right way to do this?
Posted: Wed Nov 24, 2010 5:49 pm
by pickle
If you're only replacing instances of 6 of the same character, then there's only 16 possibilities & I wouldn't bother about using preg_replace & stick with str_replace(). Better yet, use str_ireplace() and you can replace both "FFFFFF" and "ffffff" in one go.
If, however, you want to compress stuff like: #33CCFF -> #3CF, it's a different matter.
In any case, I'm wondering why you're doing this? The only conceivable reason I can think of is to reduce filesize. If that's the reason, save yourself a ton of work & just use
CSS Compressor