Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make math inside preg_replace php

I have the following string

$str = ".block_1 {width:100px;}.block_2 {width:200px;}.block_3 {width:300px;}";

I want to replace the px values with percentage values according to this formula (pixelvalue / 960) *100

I know that with such regular expression ([0-9]+px) I can find all values + px but then I need to run through it again replacing it with (pixelvalue / 960) *100.'%'

Hope you understand what I mean and thank you for any help.

Ok, here is the solution:

$str = preg_replace_callback(
        '([0-9]+px)',
        function ($matches) {            
            return ((str_replace('px','',$matches[0])/960)*100).'%';
        },
        $str
    );
    echo $str;
like image 419
devjs11 Avatar asked Jun 20 '13 15:06

devjs11


1 Answers

Have a look at preg_replace_callback

like image 182
Toto Avatar answered Sep 21 '22 04:09

Toto