İşte benim çözümdür. Bu eval() ifadeyi değerlendirmek için, ama merak etmeyin kullanır, sonunda regex onay tamamen güvenli hale getirir.
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;
}
}
Yani, örneğin, dize
3' 2 1/2"
ifade dönüştürülmüş olur
3*12+2+1/2
değerlendirilerek aldığı
38.5
Son olarak 0,9779 metre dönüştürülmüş olur ki.