Add Spaces

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
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Add Spaces

Post by donny »

Hello,

I have a form and the user can add their phone number.

if they enter their phone number 1234567891 is there a way i can change it on my processing page to
123 456 7891


thank you
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Add Spaces

Post by requinix »

If they enter a 10 (strlen) digit (ctype_digit) number, grab (substr) the first three characters, the second three, and the last four, and output them with spaces in between.

Code: Select all

if (strlen($number) == 10 && ctype_digit($number)) {
    $number = substr($number, 0, 3) . " " . substr($number, 3, 3) . " " . substr($number, 6);
}
You may want to do other things first like strip spaces and symbols.
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Re: Add Spaces

Post by donny »

i am having trouble understanding this .. i have a 9 digit number that i need to put a space after every 3 characters 123456789 to 123 456 789

thank you
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Add Spaces

Post by Celauran »

Use the above answer, but change the strlen comparison from 10 to 9.
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Re: Add Spaces

Post by donny »

perfect thank you both for your help
Post Reply