Jump to content

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

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?

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.