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?
is preg_replace the right way to do this?
Moderator: General Moderators
-
someguyhere
- Forum Contributor
- Posts: 181
- Joined: Sun Jul 27, 2008 3:24 pm
Re: is preg_replace the right way to do this?
Are you just truncating the last three characters regardless of what they are, or is it more complex than that?
-
someguyhere
- Forum Contributor
- Posts: 181
- Joined: Sun Jul 27, 2008 3:24 pm
Re: is preg_replace the right way to do this?
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.
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?
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?
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
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
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.