Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

substr, modifying phone number 1

Status
Not open for further replies.

nix45

MIS
Nov 21, 2002
478
US
I have a 7 digit phone number that I want to add a - to after the first 3 digits. I got it working, but there has to be a better and simpler way than this.

$phone = '5551234';
$phone1 = substr($phone,0,3);
$phone2 = substr($phone,3);
$phone = $phone1 . '-' . $phone2;

Thanks,
Chris
 
You only really need to use the substr function once.

Code:
my $phone = '5551234';
substr $phone, 3, 0, "-";

$phone is now '555-1234'.
 
Thanks, I knew it could be done in one line, but I couldn't remember how.

Chris
 
rharsh's solution is better however an alternative could be as follows:

$phone=~s/(\d{3})(\d{4})/$1-$2/g;

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top