is preg_replace the right way to do this?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

is preg_replace the right way to do this?

Post 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?
s992
Forum Contributor
Posts: 124
Joined: Wed Oct 27, 2010 3:06 pm

Re: is preg_replace the right way to do this?

Post by s992 »

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?

Post 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.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: is preg_replace the right way to do this?

Post 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
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: is preg_replace the right way to do this?

Post 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
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply