I'm currently building an application that will have addresses inside it and I'm using preg_match to do some character detection and throw an error the user's way if they use invalid characters to make sure it's secure.
My problem is using preg_match it seems to be behaving strangely and I don't think I'm using it correctly or not because of how it's acting.
My code below should allow letters A to Z, both upper and lowercase for the City, County and Country. The code below is an example of the city when that field is updated:
// The user wants to update the city so let's go through the update process
if ( isset($_POST['city']) ) {
// Check that the city is different before we try to update it
if ( $newcompanycity != $companycity ) {
// Check that the city is less than 50 characters and contains valid characters
if ( (strlen($newcompanycity) <= 50) && (preg_match('/[^A-Za-z]/', $newcompanycity)) ) {
// The city is fine so let's update it
$update_success = true;
mysqli_query($sql, "UPDATE clients SET city = '$newcompanycity' WHERE companyid = '$companyid'") or die(mysqli_error($sql));
} else {
// The city doesn't meet the requirements to be update so return an error
$update_fail = true;
$city_error = true;
}
}
}
Now the issue is that $city_error
is being triggered when the current value is "Sheffield" and you change it to "York" it returns an error as the $city_error
variable becomes true. However changing the value from "Sheffield" to "Sheffield 1", it then works and updates the database.
Am I missing something here? I thought that A-Za-z only checks for letters and if there are only letters then it should work. But this doesn't seem to be working at all.
Just a quick update before I posted this. I just realised I need to add a space at the end of string and then it works. I'm really confused with this. So without a space it returns an error as preg_match doesn't allow it but with a space even though it's not defined inside preg_match it allows it. Surely this isn't normal behavior?
Your regex is
/[^A-Za-z]/
which means something like "everything that is not A-Z and a-z". The preg_match function returns the number of matches, so if no invalid characters were found it should return 0.So if you change
(preg_match('/[^A-Za-z]/', $newcompanycity))
to(preg_match('/[^A-Za-z]/', $newcompanycity) === 0)
it should work as expected as it becomes true if no invalid characters where found.To include whitespaces just add them to your regex:
/[^A-Za-z ]/
.