我试图将字符串的高度转换为英寸,所以基本上字符串$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
下面是使用regexp
的解决方案<?php
$val = '5'' 10"';
preg_match('/'s*('d+)'''s+('d+)"'s*/', $val, $match);
echo $match[1]*12 + $match[2];
's*
只是在有前导或尾随空格的情况下使用。
编辑:
你传递错误的变量给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 这样可以:
$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
$parts = explode(" ",$height);
$feet = (int) preg_replace('/[^0-9]/', '', $parts[0]);
$inches = (int) preg_replace('/[^0-9]/', '', $parts[1]);