XIMRX
XIMRX

Reputation: 2172

How to read all numeric values from within a file in php?

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.

Upvotes: 0

Views: 143

Answers (2)

Toto
Toto

Reputation: 91430

Use preg_replace_callback:

$str = preg_replace_callback('/:\s*(\d+)px/', 
    function($m) {
        return ': '.($m[1]/2).'px';
    },
    $str);

Upvotes: 1

Dropout
Dropout

Reputation: 13866

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.

Upvotes: 0

Related Questions