1

I am trying to replace the first occurnce of css size(px|pt|em) with - so this:
64px 64px #123456 will become:
-64px 64px #123456

I am using the next regex:
preg_replace("/((-*\d+(?:px|e[mx]|%)?)\s(-*\d+(?:px|e[mx]|%)?)){1,1}?/si", "-$1", $input_lines);

it works great when there are only 2 sets of sizes but when there are 4 like:
64px 64px 12px 12px #123456 in get the next results:
-64px 64px -12px 12px #123456. what can I do to stop it after the first occurrence? Thanks!

4
  • Might I ask why you're modifying a CSS string with JavaScript? This sounds like a very strange use-case. Commented Nov 26, 2013 at 13:20
  • @ArunKillu : this not working and as far as I know there is no g in preg_replaec @FritsvanCampen : I am parsing css files Commented Nov 26, 2013 at 13:21
  • don't do that y you want to parse css when browser itself parse for you Commented Nov 26, 2013 at 13:23
  • 1
    Otherwise if this regexp encounters with a -64px it will modify it to - - 64px... Commented Nov 26, 2013 at 13:25

1 Answer 1

3

With the 4. argument of preg_replace you can limit how much replace you would like to do:

http://php.net/preg_replace

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

So you should use this way:

preg_replace("/((-*\d+(?:px|e[mx]|%)?)\s(-*\d+(?:px|e[mx]|%)?)){1,1}?/si",
"-$1", $input_lines, 1);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I had forgotten about this argument :-)
Oops... I've misread a question again. I've just removed my bogus comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.