0

I want to get the replace a number in a string after multiplying it by a variable. I have the following PHP:

$desc = "+2.23% critical damage";
$count = 3;`

Now I want to use the value of $count * $desc within a new string, as shown here:

$sum = "+6.69% critical damage";

How do I manage this? How can I multiply the numbers in this string with $count?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
bastianum
  • 33
  • 6

2 Answers2

0

Three possibilities.

Ugly as hell, but working (use floatval() on the string):

<?php

$desc = "+2.23% critical damage";
$count = 3;
$sum = floatval($desc) * $count . "% critical damage";
echo $sum;
# 6.69% critical damage
?>

Second: a regex approach.

<?php
# define a regex to allow digits and points directly connected
$regex = '~[\d.]+~';
preg_match($regex, $desc, $num);
$sum = floatval($num[0]) * $count . "% critical damage";
echo $sum;
# 6.69% critical damage
?>

Third possibility (probably the best): try to refine your actual requirements and edit your question :)

Jan
  • 42,290
  • 8
  • 54
  • 79
0

In case the rest of your string is dynamic, it may be more robust to replace the floating point number using preg_replace_callback() -- this way you are only touching the number in the string.

sprintf() is very handy for standardizing the format of the product.

Code: (Demo)

$desc = "+2.23% critical damage";
$count = 3;

var_export(
    preg_replace_callback(
        '~^[+-]\d+(?:\.\d+)?~',
        function($m) use ($count) {
            return sprintf('%+.2f', $m[0] * $count);
        },
        $desc,
        1
    )
);

Output:

'+6.69% critical damage'
mickmackusa
  • 43,625
  • 12
  • 83
  • 136