What are common formats for storing phone numbers in a database and how can they be standardized using PHP?
When storing phone numbers in a database, it's common to encounter different formats such as (123) 456-7890, 123-456-7890, or 1234567890. To standardize phone numbers, you can remove any non-numeric characters and ensure a consistent format across all entries. This can be achieved using PHP by using regular expressions to extract only the digits and then reformatting them as needed.
// Sample phone number with different formats
$phone_number = "(123) 456-7890";
// Remove non-numeric characters
$cleaned_number = preg_replace('/\D/', '', $phone_number);
// Format the phone number as (123) 456-7890
$formatted_number = preg_replace('/(\d{3})(\d{3})(\d{4})/', '($1) $2-$3', $cleaned_number);
echo $formatted_number; // Output: (123) 456-7890
Related Questions
- How can you replicate the functionality of PHP's shuffle() function using only basic loops and if statements, without using array functions like array_values or in_array?
- How can the value of a specific variable from a MySQL database be retrieved and used for session authentication in PHP?
- What is the difference between eregi_replace and preg_replace in PHP?