PHP to validate and sanitize phone numbers
PHP Code Solution for Validating and Sanitizing Phone Numbers
<?php
// Regular expression for validating phone numbers
$phoneRegex = '/^(?:\+?(\d{1,2}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})$/';
// Function to validate a phone number
function validatePhoneNumber($phoneNumber) {
global $phoneRegex;
return preg_match($phoneRegex, $phoneNumber);
}
// Function to sanitize a phone number
function sanitizePhoneNumber($phoneNumber) {
global $phoneRegex;
return preg_replace('/[^0-9]/', '', $phoneNumber);
}
// Test the functions
$phoneNumber = '123-456-7890';
if (validatePhoneNumber($phoneNumber)) {
echo "Valid phone number: $phoneNumber<br>";
} else {
echo "Invalid phone number: $phoneNumber<br>";
}
$sanitizedPhoneNumber = sanitizePhoneNumber($phoneNumber);
echo "Sanitized phone number: $sanitizedPhoneNumber<br>";
?>
How it Works
The code above uses regular expressions to validate and sanitize phone numbers.
Validation
The validatePhoneNumber()
function uses the preg_match()
function to check if the input string matches the $phoneRegex
regular expression. If the input string matches the regular expression, the function returns true
, indicating that the phone number is valid. Otherwise, the function returns false
.
Sanitization
The sanitizePhoneNumber()
function uses the preg_replace()
function to remove all non-digit characters from the input string. This results in a sanitized phone number that contains only digits.
How to Implement It Effectively
To implement this code effectively, you should:
- Define a clear and consistent naming convention for your functions and variables.
- Use descriptive comments to explain what your code does.
- Test your code thoroughly to ensure that it works correctly.
- Use a library or framework that provides phone number validation and sanitization functionality. This will save you time and effort, and it will help you to avoid potential security vulnerabilities.