2013-04-28 134 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