How to easily split a sequence of numbers into a hython seperate string

Posted on October 25, 2011 at 3:46 pm by boxedfish No Comment

So frist off, I have to credit this to a top bloke called @jamesmills. A good follow on twitter! A great developer and if your in the north and want a site done make sure to see this guy first.

So say you have a string 123456 and you want that to be 12-34-56 (yes thats right, a bank short code…). Well, its really simple:

<?php $ournumber = 123456; implode('-', str_split($ournumber,2)); ?>

Nothing more too it! So inside the implode is the first bit of code to look at:

str_split($ournumber,2)

That splits the string every two characters into an array.

Next, we want to glue our string back together and to do that we use the glue “-” and implode the array like so:

implode('-', str_split($ournumber,2));

One thing to note, needles and haystacks as I call them (string and array) are not constant, sometimes they follow this pattern, some times they are the other way around! so if you get a funky result, 9/10 times its because you have got it the other way around.

Enjoy.

Leave a comment