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.