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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With