tags:

views:

43

answers:

4

I have been fiddling with this for almost an hour and am getting nowhere. Regexes are not my strong suit.

I have data like the following:

.cke_button_about .cke_icon { background-position: 0 -76px; }
.cke_button_maximize .cke_icon { background-position: 0 -108px; }

I need to replace the vertical values (-76px and -108px) using preg_replace_callback(). The callback function is written, but I can't for the life of me get the numbers out properly.

This works fine for 4-digit numbers:

preg_replace_callback("/(background\-position\:)(.*)(\d{4})(px)/", "recalculate",
$css_string);

but how can I make it so it recognizes any kind of number? {1-4} should work but somehow conflicts with the first, horizontal value.

Would anybody like to help me out?

Thanks in advance.

+3  A: 

((-?)[0-9.]+) would probably be better, this would match the following cases:

  • 1.0
  • 1000
  • -400
  • 642.42
  • -642.42
  • 0

The whole code would be something like this:

preg_replace_callback("/(background\-position\:)(.*?)((-?)[0-9.]+)(px)/", "recalculate",
$css_string);
Sune Rievers
Cheers, I would accept both answers if I could :)
Pekka
Wouldn't the (.*) select the '?' any way?
Chalkey
+1 Nice to think about `-` :)
RC
Though if you are going to think about the `-`, you'll need to replace the `.*` with `.*?` or `[^-]*`.
Anon.
@Chalkey, it would, but I don't think it should? I would like the regex to extract the full number, including sign if applicable.
Sune Rievers
@Anon, true - added more code to solution :)
Sune Rievers
+1  A: 
/(background\-position\:)(\D*\d*\D*)(\d+)(px)/

Gets what you want while preserving the current capturing groupings.

Anon.
The combination of this and \d+ works, thanks a lot!
Pekka
A: 

what about preg_replace_callback("/(background\-position\:)\s*(\d+)\s+(\d{4})(px)/", "recalculate", $css_string);? + meaning "one or more"

RC
+1  A: 

Can you do (background\-position)(.*)([0-9]+)(px)?

Chalkey