dk4210 Posted February 8, 2012 Share Posted February 8, 2012 Hello Guys, I have a var for height like $height="67" and want to be able to split that number into, so that I can display 6 feet 7 inches but I have not figured out how to do it.. Please advise.. This is the current code I am working with but doesn't work. The problem is that explode won't work without some type of separator. $height2 = explode(" ", $height); echo "This is feet". $height2[0] ."<br>"; echo "This is inches". $height2[1]. "<br>"; Link to comment https://forums.phpfreaks.com/topic/256664-spliting-two-numbers/ Share on other sites More sharing options...
AyKay47 Posted February 8, 2012 Share Posted February 8, 2012 if this format is static, you can use a simple preg_replace for this. $str = 67; $pattern = "~^(\d{1})(\d{1})$~"; $replacement = '${1}\'${2}"'; echo preg_replace($pattern,$replacement,$str); or if you want the literal 6 feet 7 inches and not 6'7" $str = 67; $pattern = "~^(\d{1})(\d{1})$~"; $replacement = '${1} feet ${2} inches'; echo preg_replace($pattern,$replacement,$str); Link to comment https://forums.phpfreaks.com/topic/256664-spliting-two-numbers/#findComment-1315768 Share on other sites More sharing options...
KevinM1 Posted February 8, 2012 Share Posted February 8, 2012 Why use expensive regex when math is easier? $num = 67; $feet = (int)($num / 10); // cast to an integer, otherwise it would be 6.7. So, 6 $inches = $num % 10; // modulus means division remainder, so 7. echo "$feet feet $inches inches"; Link to comment https://forums.phpfreaks.com/topic/256664-spliting-two-numbers/#findComment-1315769 Share on other sites More sharing options...
PFMaBiSmAd Posted February 8, 2012 Share Posted February 8, 2012 Or just directly reference the two characters - echo "This is feet". $height[0] ."<br>"; echo "This is inches". $height[1]. "<br>"; P.S. How does your method of storing the feet and inches together, address 10 and 11 inches? Link to comment https://forums.phpfreaks.com/topic/256664-spliting-two-numbers/#findComment-1315773 Share on other sites More sharing options...
AyKay47 Posted February 8, 2012 Share Posted February 8, 2012 Why use expensive regex when math is easier? $num = 67; $feet = (int)($num / 10); // cast to an integer, otherwise it would be 6.7. So, 6 $inches = $num % 10; // modulus means division remainder, so 7. echo "$feet feet $inches inches"; I normally am not a big fan of creating large arrays so I tend to not use explode (habit), in this case with only a two element array, your or PFM's method would be the simplest. To answer your question.. because I like regex.... Link to comment https://forums.phpfreaks.com/topic/256664-spliting-two-numbers/#findComment-1315815 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.