"T" could be "thousand" or "trillion", you know.
$s = "15.7T";
$factors = Array('T' => 1000, 'M' => 1000000, 'B' => 1000000000.);
$matches = Array();
if (0 < preg_match('/([0-9]+(?:\.[0-9]*)?)([TMB])/', $s, $matches)) {
print("$s -> " . $matches[1] * $factors[$matches[2]]);
}
prints:
15.7T -> 15700
edit:
Anchoring (makes any garbage on the front or back mean no match):
'/^(...)$/'
You may want to make whitespace allowed, however:
'/^\s*(...)\s*$/'
You can also use "\d" in place of "[0-9]:
'/(\d+(?:\.\d*)?)([TMB])/'
Case insensitivity:
'/.../i'
...
print("$s -> " . $matches[1] * $factors[strtoupper($matches[2])]);
Optional factor:
'/([0-9]+(?:\.[0-9]*)?)([TMB])?/'
$value = $matches[1];
$factor = isset($matches[2]) ? $factors[$matches[2]] : 1;
$output = $value * $factor;
Use printf to control output formatting:
print($value) -> 1.57E+10
printf("%f", $value); -> 15700000000.000000
printf("%.0f", $value); -> 15700000000
Stephan202 recommended a clever trick, put the "?" (optional) within the parens and you're guaranteed a match string, it just might be blank. Then you can use the blank as an array key to get the default value without having to test whether it matched or not.
Putting all that together:
$factors = Array('' => 1, 'T' => 1e3, 'M' => 1e6, 'B' => 1e9);
if (0 < preg_match('/^\s*(\d+(?:\.\d*)?)([TMB]?)\s*$/i', $s, $matches)) {
$value = $matches[1];
$factor = $factors[$matches[2]];
printf("'%s' -> %.0f", $s, $value * $factor);
}