inserting a character at a certain spot in a string
Posted: Thu Nov 03, 2005 3:21 pm
I need to take a phone number and insert a - as the fourth character, making 5551234 into 555-1234. How would I go about doing so?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
I agree, it saves time when you want to switch to a new format, and not only that you're saving one character in each field, in large tables formatting characters are a waste of spaceI never like to format anything when it is being stored in a database, because I like to be able to tear it apart any way I like after it comes out.
Code: Select all
$number = '555.1234';
$digit_count = 0;
//clean out the non-digit characters. There's probably an easier/more efficient way
for($i = 0;$i < strlen($number);++$i)
{
//if the current character is a digit
if(preg_match('/\d/',$number{$i}))
{
//increment the count of digits
++$digit_count;
//if we're looking at the fourth digit, put in a dash
//before we add the digit
if($digit_count == 4)
{
$formatted_number[] = '-';
}
$formatted_number[] = $number{$i};
}
}
//$formatted_number should now contain '555-1234';Code: Select all
<?php
$number = '555.1234';
$number = substr($number = preg_replace('/[^0-9]/', '', $number), 0, 3) . '-' . substr($number, 3);
?>Genius.redmonkey wrote:How about...Code: Select all
<?php $number = '555.1234'; $number = substr($number = preg_replace('/[^0-9]/', '', $number), 0, 3) . '-' . substr($number, 3); ?>
Code: Select all
<?php
$number = '5551234';
$number = substr($number, 0, 3) . '-' . substr($number, 3);
?>I tend not to format anything when storing in a db. Let's see is there anything I format? uhh...timvw wrote:My advise is to store them without any formatting.. It's a phonenumber..
When displaying them to the user you can offcourse use the prefered/localized format..