3

ここで、すでに 100 万回解決されていると私が信じている (または少なくとも望んでいる) 問題に直面しています。入力として取得したのは、オブジェクトの長さを帝国単位で表す文字列です。次のようになります。

$length = "3' 2 1/2\"";

またはこのように:

$length = "1/2\"";

または実際には、私たちが通常それを書く他の方法で。

世界的な車輪の発明を減らすために、インペリアルの長さをメートルの長さに変換できる関数、クラス、または正規表現のようなものがあるかどうか疑問に思いますか?

4

5 に答える 5

4

Zend Framework には、まさにその目的のための測定コンポーネントがあります。ここで確認することをお勧めします。

$unit = new Zend_Measure_Length($length,Zend_Measure_Length::YARD);
$unit -> convertTo(Zend_Measure_Length::METER);
于 2008-11-28T07:55:12.090 に答える
3

これが私の解決策です。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 メートルに変換されます。

于 2008-11-28T06:58:56.680 に答える
2

インペリアル文字列の値はもう少し複雑なので、次の式を使用しました。

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;
于 2010-07-21T15:31:01.667 に答える
1

おそらく単位ライブラリをチェックしてください。ただし、それに対する PHP バインディングはないようです。

于 2008-11-28T06:02:56.137 に答える
1

正規表現は次のようになります。

"([0-9]+)'\s*([0-9]+)\""

(\s は空白を表します - PHP でどのように機能するかはわかりません)。次に、最初の + 2 番目のグループを抽出して実行します

(int(grp1)*12+int(grp2))*2.54

センチメートルに換算します。

于 2008-11-28T06:04:09.317 に答える