Connecting Tech Pros Worldwide Help | Site Map

how split number 3 parts

Member
 
Join Date: Mar 2008
Posts: 45
#1: Sep 30 '09
hi,
i have a number with 9 digits lenght
and i want split this number: 922888222
into this: 922 888 222
how can i do that?
thanks a lot for your help :)
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#2: Sep 30 '09

re: how split number 3 parts


you can use a RegEx (preg_replace()).
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,936
#3: Sep 30 '09

re: how split number 3 parts


Quote:

Originally Posted by Dormilich View Post

you can use a RegEx (preg_replace()).

preg_split() would be better ;)

And str_split() better still - pay attention to the optional 'length' parameter.
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#4: Sep 30 '09

re: how split number 3 parts


Quote:

Originally Posted by Markus View Post

preg_split() would be better

that depends on the desired output.
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,936
#5: Sep 30 '09

re: how split number 3 parts


Quote:

Originally Posted by Dormilich View Post

that depends on the desired output.

I don't think the output is in question - the OP asked for his string to be split.
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#6: Sep 30 '09

re: how split number 3 parts


the OP didn’t mention to split it into an array. you know how loose the meaning of a word can be in this forum.
TheServant's Avatar
Expert
 
Join Date: Feb 2008
Location: Australia
Posts: 913
#7: Sep 30 '09

re: how split number 3 parts


I am presuming that it is a phone number or the like that the OP wants formatted. How I would do it, not saying Dorms way won't work or be better, but str_split() and then a simple echo with spaces. It can be done in a loop if the length of the original number is variable, but I think this will do:
Expand|Select|Wrap|Line Numbers
  1. $number = "922888222";
  2. $array = str_split($number,3); // Splits the number into a new element every 3 characters
  3. echo( $array[0],' ', $array[1],' ', $array[2] ); // Ouputs each element with a space in between
zorgi's Avatar
Member
 
Join Date: Mar 2008
Location: here
Posts: 107
#8: Oct 1 '09

re: how split number 3 parts


I would probably do it like this


Expand|Select|Wrap|Line Numbers
  1. number_format(922888222, 0, " ", " ");
  2.  
http://hr.php.net/number_format
TheServant's Avatar
Expert
 
Join Date: Feb 2008
Location: Australia
Posts: 913
#9: Oct 1 '09

re: how split number 3 parts


Quote:

Originally Posted by zorgi View Post

I would probably do it like this


Expand|Select|Wrap|Line Numbers
  1. number_format(922888222, 0, " ", " ");
  2.  
http://hr.php.net/number_format

Great idea! Looks like it would work.
Reply