What are some alternative methods or functions in PHP that can be used to format phone numbers with specific requirements, such as separating the main number from extensions or special characters?

When formatting phone numbers in PHP, you may need to separate the main number from extensions or add special characters like dashes or parentheses. One way to achieve this is by using regular expressions to match specific patterns in the phone number string and then format it accordingly.

// Function to format phone numbers with specific requirements
function formatPhoneNumber($phoneNumber) {
    // Remove all non-numeric characters from the phone number
    $phoneNumber = preg_replace('/\D/', '', $phoneNumber);
    
    // Check if the phone number has an extension
    if (preg_match('/(\d{3})(\d{3})(\d{4})(\d{1,4})/', $phoneNumber, $matches)) {
        // Format the phone number with main number and extension
        $formattedNumber = '(' . $matches[1] . ') ' . $matches[2] . '-' . $matches[3] . ' ext. ' . $matches[4];
    } else {
        // Format the phone number with main number only
        $formattedNumber = '(' . substr($phoneNumber, 0, 3) . ') ' . substr($phoneNumber, 3, 3) . '-' . substr($phoneNumber, 6);
    }
    
    return $formattedNumber;
}

// Example usage
$phoneNumber = '123-456-7890 ext. 1234';
$formattedPhoneNumber = formatPhoneNumber($phoneNumber);
echo $formattedPhoneNumber;