Can't get any preg_match to work

I’m trying to use preg_match on a users address input and no matter what I try they are all wrong, and I must have tried 50 different ways. I’m hoping someone can help me out.

I simply want to include numbers and letters, apostrophe, space, period, and hyphen. Below is the latest rendition of what I have tried.

$address = "55 My'Road-West Ave.";

if (!preg_match('/^[a-z0-9 :,.!().?";\'-]+$/i', $address)) { $error['address'] = 1; }

Thanks

I think this is the culprit, I have a function that cleans the user input, and if I remove it the preg_match works.

function Sanitize($input) {
    $input = trim($input);
    $input = stripcslashes($input);
    $input = htmlspecialchars($input, ENT_QUOTES);
    return $input;
}

Any help with this mess is appreciated.

For the regex pattern, use - "/^[a-z0-9' .-]+$/i" Note: I switched to overall double-quotes so that the single-quote/apostrophe can be un-escaped.

As to the function code, you are validating data, to make sure it meets the business needs of your application. If data is valid, you use it, safely. If it is not valid, you let the user know what was wrong with it, let them correct the problem, and resubmit the data. Other than trimming data, so that you can detect if all white-space characters were entered, do NOT modify the data, as this changes the meaning of the data.

Forget about any strip____() function. htmlspecialchars() is an OUTPUT function. You use it when you output dynamic values in a html context. Do NOT us it on input data that you are trying to validate as it changes the meaning of the data.

2 Likes
Sponsor our Newsletter | Privacy Policy | Terms of Service