【问题标题】:How to multiplicate 2 numbers in one string with 3rd outside the string in PHP?如何将一个字符串中的 2 个数字与 PHP 中字符串之外的第 3 个数字相乘?
【发布时间】:2022-01-19 11:57:07
【问题描述】:

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




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

【问题讨论】:

    标签: php regex


    【解决方案1】:

    你可以使用

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

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

    【讨论】:

    • how can make them back in the sentence , like my strings is $string = "This is 225cm x70 cm coating" 怎么会变成 This is 85.5'' x 27.5'' 服装?
    • @Bulgarian_power echo preg_replace_callback('/\d+(?:\.\d+)?/', function($m) { return round(intval($m[0]) * 0.39370 / 0.5) * 0.5 . '"'; }, $string);,见the PHP demo
    • 哇好!非常感谢!
    猜你喜欢
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2020-02-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多