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

问题描述 投票:0回答:4

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

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

或者像这样:

$length = "1/2\"";

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

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

php regex code-snippets
4个回答
4
投票

Zend Framework 有一个专门用于此目的的测量组件。我建议你检查一下 - 这里

$unit = new Zend_Measure_Length($length,Zend_Measure_Length::YARD);
$unit -> convertTo(Zend_Measure_Length::METER);

3
投票

这是我的解决方案。它使用 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 米。


2
投票

英制字符串值有点复杂,所以我使用了以下表达式:

string pattern = "(([0-9]+)')*\\s*-*\\s*(([0-9])*\\s*([0-9]/[0-9])*\")*";
Regex regex = new Regex( pattern );
Match match = regex.Match(sourceValue);
if( match.Success ) 
{
    int feet = 0;
    int.TryParse(match.Groups[2].Value, out feet);
    int inch = 0;
    int.TryParse(match.Groups[4].Value, out inch);
    double fracturalInch = 0.0;
    if (match.Groups[5].Value.Length == 3)
         fracturalInch = (double)(match.Groups[5].Value[0] - '0') / (double)(match.Groups[5].Value[2] - '0');

    resultValue = (feet * 12) + inch + fracturalInch;

1
投票

正则表达式看起来像这样:

"([0-9]+)'\s*([0-9]+)\""

(其中 \s 代表空格 - 我不确定它在 php 中是如何工作的)。然后提取第一组+第二组并执行

(int(grp1)*12+int(grp2))*2.54

转换为厘米。

© www.soinside.com 2019 - 2024. All rights reserved.