在这里,我面临一个我相信(或至少希望)已经解决了 100 万次的问题。我作为输入得到的是一个字符串,它以英制单位表示对象的长度。它可以是这样的:
$length = "3' 2 1/2\"";
或像这样:
$length = "1/2\"";
或者实际上我们通常会以任何其他方式编写它。
为了减少全球车轮发明,我想知道是否有一些函数、类或正则表达式允许我将英制长度转换为公制长度?
在这里,我面临一个我相信(或至少希望)已经解决了 100 万次的问题。我作为输入得到的是一个字符串,它以英制单位表示对象的长度。它可以是这样的:
$length = "3' 2 1/2\"";
或像这样:
$length = "1/2\"";
或者实际上我们通常会以任何其他方式编写它。
为了减少全球车轮发明,我想知道是否有一些函数、类或正则表达式允许我将英制长度转换为公制长度?
Zend 框架有一个用于此目的的测量组件。我建议你检查一下 -在这里。
$unit = new Zend_Measure_Length($length,Zend_Measure_Length::YARD);
$unit -> convertTo(Zend_Measure_Length::METER);
这是我的解决方案。它使用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 米。
英制字符串值有点复杂,所以我使用了以下表达式:
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;
也许查看单位库?不过,它似乎没有 PHP 绑定。
正则表达式看起来像这样:
"([0-9]+)'\s*([0-9]+)\""
(其中 \s 代表空格 - 我不确定它在 php 中是如何工作的)。然后你提取第一+第二组并做
(int(grp1)*12+int(grp2))*2.54
转换为厘米。