How to convert imperial units of length into metric?

前端 未结 5 1759
心在旅途
心在旅途 2021-01-14 07:16

Here I am faced with an issue that I believe(or at least hope) was solved 1 million times already. What I got as the input is a string that represents a length of an object

5条回答
  •  生来不讨喜
    2021-01-14 08:10

    Here is my solution. It uses eval() to evaluate the expression, but don't worry, the regex check at the end makes it completely safe.

    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;
        }
    }
    

    So for example, the string

    3' 2 1/2"
    

    gets converted to the expression

    3*12+2+1/2
    

    which gets evaluated to

    38.5
    

    which finally gets converted to 0.9779 meters.

提交回复
热议问题