php validate string with preg_match

19,410

Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'

So:

$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
    #your string is good
}

Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.

Share:
19,410
NVG
Author by

NVG

Updated on July 10, 2022

Comments

  • NVG
    NVG almost 2 years

    I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.

    I tried to search on google but I could not find anything usefull.

    Can anybody help?

    Thank you !