Page 1 of 1

a small string question

Posted: Thu Mar 06, 2008 4:08 am
by itsmani1
I have a sting like "03335240141" i want display it like 0333-524-0141 is there any string function that can do this for me?

thank you
dizyn

Re: a small string question

Posted: Thu Mar 06, 2008 9:03 am
by Sekka
There's no built in function for formatting strings like that, however, this should do the trick,

Code: Select all

function format ($str) {
    
    // Validate
    if (!is_string ($str) || strlen ($str) != 11) {
        return false;
    }
    
    // Format
    return substr ($str, 0, 4) . "-" . substr ($str, 4, 3) . "-" . substr ($str, 7);
    
}

Re: a small string question

Posted: Thu Mar 06, 2008 12:35 pm
by kryles
that is if the dash is ALWAYS in the same spot though. So be sure.

Re: a small string question

Posted: Thu Mar 06, 2008 12:53 pm
by John Cartwright
Assuming actually wanted the 2nd octet to only be 3 characters,

xxxx-xxx-xxxx format

Code: Select all

function formatID ($id) 
{
    return preg_replace('#(\d{4})(\d{3})(\d{4})#', '$1-$2-$3', $id);
}
xxxx-xxxx-xxx format (which is what I'd expect personally)

Code: Select all

 
function formatID2($id) 
{
    return implode('-', str_split($id, 4));
}