a small string question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

a small string question

Post 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
User avatar
Sekka
Forum Commoner
Posts: 91
Joined: Mon Feb 18, 2008 10:25 am
Location: Huddersfield, West Yorkshire, UK

Re: a small string question

Post 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);
    
}
kryles
Forum Contributor
Posts: 114
Joined: Fri Feb 01, 2008 7:52 am

Re: a small string question

Post by kryles »

that is if the dash is ALWAYS in the same spot though. So be sure.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: a small string question

Post 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));
}
 
Post Reply