Jump to content

Spliting two numbers


dk4210

Recommended Posts

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

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);

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....  :P

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.