How to do math inside preg_replace php

I have the following line

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

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

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

I 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; 
+4
source share
1 answer

Take a look at preg_replace_callback

+9
source

Source: https://habr.com/ru/post/1487322/


All Articles