I am trying to use an if statement to determine if a certain variable in PHP ($phone) matches a regular expression. There are three different options – it either passes it correctly, it is a mostly correct value and just needs some slight modifications, and finally, that it is an an erroneous value and should go back to the previous page with an error message. Here’s what I’ve got so far:
EDIT: The expected value of $phone is either 123-456-7890, 1234567890, or (123) 456-7890. The desired input for the database is 123-456-7890
if (preg_match("/^\d{3}-\d{3}-\d{4}$/", $phone)) {
// This is the 100% correct version
}
else if (preg_match("/^\d{10}$/", $phone)) {
$phone = preg_replace("/^(.{3})/", "-", $phone);
$phone = preg_replace("/^(.{6})/", "-", $phone);
// This is one of the mostly correct - this does not seem to work. I got a value of -37 when I tried to use it
}
else if (preg_match("/^\(\d{3}\) \d{3}-\d{4}$/", $phone)) {
// Have not tried anything here, because the problems here are similar to the else if statement above
}
else {
header('Location: '.$admin.'?error=phone');
// This should direct back to the previous page with an error message.
}
EDIT 2: Ok I’ve got the if and the else ifs working, however the else does not redirect back to the page or prevention insertion into the database. How do I do this?
How about:
and for the second
Explanation:
replacement part :
For dealing with all test cases, I’d do: