繁体   English   中英

如何将一个字符串中的 2 个数字与 PHP 中字符串外的第三个数字相乘?

[英]How to multiplicate 2 numbers in one string with 3rd outside the string in PHP?

我想用字符串之外的公式计算字符串,有时我得到两个数字用空格分隔的字符串,而我的公式只是计算字符串中的第一个数字。




$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"

您可以使用

$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

请参阅PHP 演示

使用preg_match_all('/\d+(?:\.\d+)?/', $string, $m) ,您将所有数字提取到$m[0]中,然后在array_map中处理每个数字,然后加入结果用implode变成一个字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM