0

I have a CSS file with numeric values with appending px like "width: 500px;". I need to read this file from start to end using php and alter all numeric values wherever found .i.e. convert 500px to some thing else like 50% of it (width: 250px). How can we do this, maybe using regex.

$file = fopen("file.css", "r+") or exit("Unable to open file!");
while(!feof($file))
{
if(numeric value between space and px)
//replace by its 50%
}
fclose($file);

This code is just to explain problem, solution can be entirely different.

3
  • Maybe you should take a look at is_numeric() Commented Feb 28, 2014 at 7:25
  • No is_numeric() doesn't work in this case. Commented Feb 28, 2014 at 7:44
  • You can probably just use php to change text in your css. Using a mycss.php file will get you variables which may be more reliable and faster than parsing with replacements. That is if this isn't a one time thing. If you need to change these values often I recommend a php file. Commented Feb 28, 2014 at 8:12

2 Answers 2

1

Use preg_replace_callback:

$str = preg_replace_callback('/:\s*(\d+)px/', 
    function($m) {
        return ': '.($m[1]/2).'px';
    },
    $str);
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you need the px? \b\d+ would select all numbers just fine including em etc...
@Robin: OP wants to convert values in px only.
0

The regex you are probably looking for is

^[\d]*(\.\d*)?(px)?(%)?(em)?$

or without decimal values

^[\d]*(px)?(%)?(em)?$

This should match all the sizes.. If you want also colors (RGB/RGBA format) then take a look at this question which might inspire you.

2 Comments

Wait, need to take into account decimal numbers.. I will update it soon.
The [...] are useless around \d, which is already a shortcut for [0-9].

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.