I want to calculate strings with formula which is outside of the string , some times i get strings with two numbers separated by space and my formula just calculate the first number from the string.
$string = "225cm x 70cm";
$outputString = preg_replace('/[^0-9]/ ', ' ', $string);// output here is string(12) "225 70 "
$inches = intval($outputString) * 0.39370;
$inches_pre = round($inches / 0.5) * 0.5; // output here is just 85 instead of string "85.5 27.5"
CodePudding user response:
You can use
$string = "225cm x 70cm";
if (preg_match_all('/\d (?:\.\d )?/', $string, $m)) {
$inches = implode(" ", array_map(function ($x) { return round(intval($x) * 0.39370 / 0.5) * 0.5; }, $m[0]));
echo $inches;
}
// => 85.5 27.5
See the PHP demo.
With preg_match_all('/\d (?:\.\d )?/', $string, $m)
, you extract all numbers into $m[0]
, and then you process each inside an array_map
and then join the results into a single string with implode
.