将var中的数字替换为另一个数字


Replace number in var with another number

我试图从字符串中获取一个数字,将其除以3,然后将原始数字替换为输出。

$original = "55 dogs";
preg_replace("/[^0-9]/","",$original);
$str = $original/ 3;
round($str);
str_replace(numbers, newNumbers, $str);
echo $str;

我通过谷歌找到了str_replace,但我不确定这是否是我想要实现的正确方法。如果有人知道一个方法,我将不胜感激。

可以使用preg_replace_callback():

$original = "55 dogs";
$result = preg_replace_callback(
            '/('d+)/',
            function($match) {
                // You can do whatever you want to do with the match here
                return round($match[0]/3); 
            },
            $original
    );
var_dump($result); // string(7) "18 dogs"