Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts

    splitting a number

    this is probably simple...but can someone help me out.
    i have variable $var=some number.the number can be of any length.examples 112,9912 etc.
    i need to split each digit and seperate it by a /
    For example,if $var=6066, I need to split it and store in a variable as /6/0/6/6/..

  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,642
    Thanks
    2
    Thanked 405 Times in 397 Posts
    Not sure if you intended to include that comma in the number or not, but this handles with/without comma:
    PHP Code:
    $numbers = array('123456''123,456');

    foreach(
    $numbers as $v)
    {
        
    $v str_replace(','''$v);
        
    var_dump('/' implode('/'str_split($v1))); // outputs "/1/2/3/4/5/6"


  • Users who have thanked Inigoesdr for this post:

    coding_begins (11-23-2011)

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    There are several ways to accomplish this. I'm lazy, so I'd make use of wordwrap to force it.
    PHP Code:
    $num 6066;
    $separated wordwrap($num1"/"true); 
    Super easy to do. You'll need to prepend and append the / if you want to keep it, but that's easy enough to do.

  • Users who have thanked Fou-Lu for this post:

    coding_begins (11-23-2011)

  • #4
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    This will remove all non-digits (commas, etc) as well as append/prepend slashes:
    PHP Code:
    $num '1,129,912';

    $num preg_replace( array( '/\D/''//' ), array( '''/' ), $num );

    echo 
    $num
    Output:
    Code:
    /1/1/2/9/9/1/2/
    Last edited by kbluhm; 11-23-2011 at 10:04 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •