Vasco
Vasco

Reputation: 301

Replace a number in var with another number

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

Answers (3)

n-dru
n-dru

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

hash-set
hash-set

Reputation: 315

$tempr=(explode(" ",$varname));
$num = $tempr[0] ; 
$newnum = $tempr[0]/5;
$newvar=$newnum." ".$tempr[1];

that will work hopefully

Upvotes: 0

Marc
Marc

Reputation: 3709

I would use str_replace (reference) and intval (reference) (and as you mentioned round):

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

Would output:

+2 cars

Upvotes: 1

Related Questions