Reputation: 301
I've got a var
with the following content: +5 cars
.
Now I want to take the numeric character, divide it by 3 and replace the current number with the new number. But I have no idea how to approach this. I've Googled for this and it lead me to preg_replace
but it can't really be that difficult, can it?
Now obviously, 5 can't be divided by 3, that's why I want it to round()
. If anybody knows a way to accomplish this, I'd appreciate it.
Upvotes: 1
Views: 102
Reputation: 9430
Just cast it as integer and replace by the result of division:
$s = "+5 cars";
$num = intval($s); // or $num = (int) $s;
$s = str_replace($num, round($num/3), $s);
echo $s;
//+2 cars
Or, using preg_match_all
:
preg_match_all('/\d+/',$s, $matches);
$s = str_replace($matches[0][0], round($matches[0][0]/3), $s);
Upvotes: 1
Reputation: 315
$tempr=(explode(" ",$varname));
$num = $tempr[0] ;
$newnum = $tempr[0]/5;
$newvar=$newnum." ".$tempr[1];
that will work hopefully
Upvotes: 0