Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex not working as intended with hyphen in a character class [duplicate]

I have this code, but is not working as I expect.

If I write #$% or textwithouterrors the message showed is "correct". So, the regex is not working.

I need to avoid, special characters, spaces and numbers

function validateCity($form) {
    if (preg_match("/[\~!\@#\$\%\^\&*()_+\=-[]{}\\|\'\"\;\:\/\?.>\,\<`]/", $form['city'])) {
        echo ("error");
        return false;
    } else {
        echo("correct");
        return true;
    }
}
validateCity($form);
like image 709
daniel__ Avatar asked Dec 09 '25 10:12

daniel__


2 Answers

There are lots of problems - The hypen - should be moved to first or end or escaped otherwise it will be seen as indicating a range. The [] have to be escaped.

Try out what you want in some place like http://gskinner.com/RegExr/

Also you are including lot of stuff in it. Just use something like \w+ as the match for a valid one rather than looking for an invalid one.

like image 152
manojlds Avatar answered Dec 11 '25 23:12

manojlds


Try reversing your logic. Look for the characters you want, not the ones you don't want.

like image 36
Daniel A. White Avatar answered Dec 12 '25 01:12

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!