Split integer from database

Discussion in 'PHP' started by PoPSiCLe, May 29, 2009.

  1. #1
    I have a database field where a phone-number is stored as an integer value - it's 8 digits, like: 12345678

    I would like to split this up when presenting it on the page, into 3 2 3 - ie: 123 45 678 for displaying.

    How can I do this the easiest way?

    I've pondered if preg_replace maybe is overkill, and was wondering if there is any simpler ways to split this string into 3 separate entities, or just somehow insert whitespace after the first 3 and the first 5 numbers.

    There will always be 8 digits in the field, but since it's being stored as an integer value, I cannot add whitespace to the database value.

    Anyone?

    EDIT: came up with this - it works, but is there an easier/prettier way to do this?
    
    
    			$phone = substr($res_info['who_phone'],0,3);
    			$phone .= " ".substr($res_info['who_phone'],3,2);
    			$phone .= " ".substr($res_info['who_phone'],5,3);
    
    PHP:
     
    PoPSiCLe, May 29, 2009 IP
  2. php-lover

    php-lover Active Member

    Messages:
    261
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    58
    #2
    ereg ("([0-9]{3})([0-9]{2})([0-9]{3})", '12345678', $part);
    echo "$part[1] - $part[2] - $part[3]";
    PHP:
    :)
     
    php-lover, May 30, 2009 IP
    PoPSiCLe likes this.
  3. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #3
    Hi, you can try this too

    
    echo preg_replace('#^(\d*)(\d{2})(\d{3})$#','$1 $2 $3','12345678');
    
    PHP:
    :)
     
    koko5, May 30, 2009 IP
    PoPSiCLe likes this.
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    Thanks to both of you - I ended up using koko5s solution - less lines of code == good :)

    +Rep added to both
     
    PoPSiCLe, May 30, 2009 IP