Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply numbers in mixed string

My trouble is to multiply numbers in string that contains various characters.

For example,

Input:

$k     = 2;    
$input = '<div style="padding:10px 15px; font-size:1em ;height:2%;"></div>';

Output:

<div style="padding:20px 30px; font-size:2em ;height:4%;"></div>

Edit

$k can be any whole number (0-9). All numbers from $input string are multiplied by $k.

like image 254
enloz Avatar asked Nov 29 '22 17:11

enloz


1 Answers

I'd use preg_replace_callback:

$input = '<div style="padding:10px 15px; font-size:1em ;height:2%;"></div>';
$output = preg_replace_callback('/([0-9]+)\s*(px|em|%)/i', function($matches){
   $k = 2;
   return ($matches[1] * $k).$matches[2];
}, $input);

The above only replace numbers followed by px, em or %.

You could also provide $k to the lambda function yourself, for more flexibility:

$k = 2;
$output = preg_replace_callback('/([0-9]+)\s*(px|em|%)/i', function($matches) use ($k){
   return ($matches[1] * $k).$matches[2];
}, $input);
like image 157
netcoder Avatar answered Dec 04 '22 01:12

netcoder