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


Replace a number in var with another number

我有一个var,内容如下:+5 cars

现在我想取数字字符,将其除以3,然后用新数字替换当前数字。但我不知道该怎么做。我已经在谷歌上搜索过了,它让我找到了preg_replace,但它不会真的那么难,是吗?

现在很明显,5不能被3整除,这就是为什么我想要它为round()。如果有人知道如何做到这一点,我将不胜感激。

我将使用str_replace(参考(和intval(参考((如您所述(:

$test = '+5 cars';
$test = str_replace(intval($test),round($test/3),$test);
echo $test;

将输出:

+2 cars

只需将其强制转换为整数并替换为除法结果:

$s = "+5 cars";
$num = intval($s); // or $num = (int) $s;
$s = str_replace($num, round($num/3), $s);
echo $s;
//+2 cars

或者,使用preg_match_all:

preg_match_all('/'d+/',$s, $matches);
$s = str_replace($matches[0][0], round($matches[0][0]/3), $s);
$tempr=(explode(" ",$varname));
$num = $tempr[0] ; 
$newnum = $tempr[0]/5;
$newvar=$newnum." ".$tempr[1];

这将有望实现