编程语言
首页 > 编程语言> > php – 如何将英制单位长度转换为公制?

php – 如何将英制单位长度转换为公制?

作者:互联网

在这里,我面临一个我相信(或至少希望)已经解决了100万次的问题.
我得到的输入是一个字符串,表示以英制单位表示的对象长度.它可以像这样:

$length = "3' 2 1/2\"";

或者像这样:

$length = "1/2\"";

或者实际上我们通常会以任何其他方式编写它.

为了减少全局轮发明,我想知道是否有一些函数,类或正则表达式可以让我将英制长度转换为公制长度?

解决方法:

这是我的解决方案.它使用eval()来评估表达式,但不要担心,最后的正则表达式检查使它完全安全.

function imperial2metric($number) {
    // Get rid of whitespace on both ends of the string.
    $number = trim($number);

    // This results in the number of feet getting multiplied by 12 when eval'd
    // which converts them to inches.
    $number = str_replace("'", '*12', $number);

    // We don't need the double quote.
    $number = str_replace('"', '', $number);

    // Convert other whitespace into a plus sign.
    $number = preg_replace('/\s+/', '+', $number);

    // Make sure they aren't making us eval() evil PHP code.
    if (preg_match('/[^0-9\/\.\+\*\-]/', $number)) {
        return false;
    } else {
        // Evaluate the expression we've built to get the number of inches.
        $inches = eval("return ($number);");

        // This is how you convert inches to meters according to Google calculator.
        $meters = $inches * 0.0254;

        // Returns it in meters. You may then convert to centimeters by
        // multiplying by 100, kilometers by dividing by 1000, etc.
        return $meters;
    }
}

例如,字符串

3' 2 1/2"

转换为表达式

3*12+2+1/2

得到评估

38.5

最终转换为0.9779米.

标签:php,regex,code-snippets
来源: https://codeday.me/bug/20190717/1485793.html