2013-04-28 26 views
-1

我試圖將字符串的高度轉換爲英寸,所以基本上字符串$height = "5' 10\""需要轉換爲70英寸。如何從字符串中提取整數

我該如何去取得字符串中的兩個int值?

這是我的數據庫更新文件

$height = $_GET['Height']; 

$heightInInches = feetToInches($height); //Function call to convert to inches 

的部分這是我的函數的高度換算成英寸:

function feetToInches($height) { 
preg_match('/((?P<feet>\d+)\')?\s*((?P<inches>\d+)")?/', $feet, $match); 
$inches = (($match[feet]*12) + ($match[inches])); 

return $inches; 

} 

它只是輸出0每次。

回答

0

這會工作:

$height = "5' 10\""; 

$height = explode("'", $height);  // Create an array, split on ' 
$feet = $height[0];     // Feet is everything before ', so in [0] 
$inches = substr($height[1], 0, -1); // Inches is [1]; Remove the " from the end 

$total = ($feet * 12) + $inches;  // 70 
0
$parts = explode(" ",$height); 

$feet = (int) preg_replace('/[^0-9]/', '', $parts[0]); 

$inches = (int) preg_replace('/[^0-9]/', '', $parts[1]); 
1

這是以防萬一用正則表達式

<?php 
$val = '5\' 10"'; 
preg_match('/\s*(\d+)\'\s+(\d+)"\s*/', $val, $match); 
echo $match[1]*12 + $match[2]; 

\s*是一個解決方案有前導或尾隨空格。

http://ideone.com/qoa6xu


編輯:
你傳遞了​​錯誤的變量preg_match,通過$height變量

function feetToInches($height) { 
    preg_match('/((?P<feet>\d+)\')?[\s\xA0]*((?P<inches>\d+)")?/', $height, $match); 
    $inches = (($match['feet']*12) + ($match['inches'])); 

    return $inches; 
} 

http://ideone.com/1T28sg

+0

我用''/((P d)\')\ s *((?P \ d +)「)?/''將英寸或腳不在比賽中。然後爲了簡化命名參數。但除此之外幾乎相同。 – 2013-04-28 05:50:07

+0

我不知道爲什麼,但我不能得到它的工作,我認爲這與我得到字符串的方式有關。它通過$ _GET數組訪問,有什麼我需要改變? $ height = $ _GET ['Height'];然後我調用$ heightInInches = feetToInches($ height); – 2013-04-28 21:27:46

+0

@PatrickYouells顯示您的代碼 – Musa 2013-04-28 21:30:58