问题描述
在这里,我面临着一个我认为(或至少希望)已经解决了100万次的问题。
作为输入,我得到的是一个字符串,它以英制单位表示对象的长度。它可以像这样:
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 in imperial units. It can go like this:
$length = "3' 2 1/2\"";
或类似这样:
$length = "1/2\"";
或实际上我们通常会以其他任何方式编写它。
or in fact in any other way we normally would write it.
为了减少全球车轮发明,我想知道是否有某些功能,类或正则表达式可以让我将英制长度转换为公制长度?
In effort to reduce global wheel invention, I wonder if there is some function, class, or regexp-ish thing that will allow me to convert Imperial length into Metric length?
推荐答案
这是我的解决方案。它使用来评估表达式,但是不用担心,最后的正则表达式检查使它成为可能完全安全。
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;
}
}
例如,字符串
3' 2 1/2"
将转换为表达式
3*12+2+1/2
评估为
38.5
最终转换为0.9779米。
which finally gets converted to 0.9779 meters.
这篇关于如何将英制长度单位转换为公制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!