How can regular expressions be used in PHP to validate and format phone numbers according to specific criteria?

Regular expressions can be used in PHP to validate and format phone numbers according to specific criteria by defining a pattern that the phone number must match. This pattern can include rules for the format of the phone number, such as the number of digits, presence of certain characters like parentheses or dashes, and the allowed range of values for each digit. By using regular expressions, you can ensure that phone numbers entered by users adhere to a standardized format, making it easier to process and validate them.

$phone_number = "+1 (555) 123-4567"; // Example phone number

// Define the regular expression pattern for a valid phone number
$pattern = "/^\+?[1-9]{1}[0-9]{2}\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/";

// Validate the phone number against the pattern
if (preg_match($pattern, $phone_number)) {
    echo "Phone number is valid.";
} else {
    echo "Invalid phone number.";
}