Skip to content
PHP Logo

What are alternative approaches to standardizing phone number formats in PHP, such as using separate input fields for area codes and numbers?

Standardizing phone number formats in PHP can be achieved by using separate input fields for area codes and numbers. This approach allows for better control over the format of the phone number and makes it easier to validate and sanitize the input. By breaking the phone number into distinct parts, it becomes simpler to manipulate and format the data as needed.

php
<form>
  <input type="text" name="area_code" maxlength="3" placeholder="Area Code">
  <input type="text" name="phone_number" maxlength="10" placeholder="Phone Number">
</form>

<?php
$area_code = $_POST['area_code'];
$phone_number = $_POST['phone_number'];

$phone_number_formatted = '(' . substr($area_code, 0, 3) . ') ' . substr($phone_number, 0, 3) . '-' . substr($phone_number, 3);

echo $phone_number_formatted;
?>