# Convert or parse a string containing feet and Inches to number in PHP

795

In my database, there is a field called height that is a varchar(9) field. The end user selects a value from a pull-down list that contains values such as:

5' 0
5' 0 1/2
5' 1
5' 1 1/2
5' 2
5' 2 1/2
And so on up to...
7' 4

What I need to do is convert this string into numeric inches for the purpose of a server-side calculation. I don't know how to approach this string conversion, so any assistance will be very much appreciated. Thank you!

227

#### Solution:

you want to get separate variables for feet, inches and fraction first

\$toBeConverted = "5' 4 1/2";
list(\$feet,\$inches,\$frac) = explode(' ',\$toBeConverted . ' ');

\$total = ((str_replace("'",'',\$feet) * 12) + \$inches + (\$frac == '1/2' ? (1/2) : 0));
919

#### Solution:

\$inches=0;
\$array=explode(" ",\$string);//where \$string is "5' 0 1/2" for example
if (\$array[2]='1/2') \$inches=(int)\$array[0]*12+(int)\$array[1]+0.5;
else \$inches=(int)\$array[0]*12+(int)\$array[1];
967

#### Solution:

If you know the index of the pulldown, with the first value being 0, then the number of inches is

\$inches = 60 + \$pulldownIndex * 0.5;

Since you start at5' (5 * 12 = 60) and go up in increments of 0.5 inch.

Alternately, if you want to look at the string that was on the pulldown, I suggest you look at Felix's answer - it is very compact and elegant.

People are also looking for solutions to the problem: php - removing characters from string if it's not in the regex

Source