Php checks string using preg_match

I am trying to verify in PHP with preg_match that the input line contains only the characters "az, AZ, -, _, 0-9". If it contains only these, then confirm.

I tried to do a google search but didn't find anything useful.

Does anyone help?

Thanks!

+4
source share
2 answers

Use the pattern '/^[A-Za-z0-9_-]*$/' if the 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 the “-” character last in the character class as part of the character class, so it reads like a “-” literal, not a stroke between two characters, such as a hyphen between AZ.

+3
source
 $data = 'abc123-_'; echo preg_match('/^[\w|\-]+$/', $data); //match and output 1 $data = 'abc..'; echo preg_match('/^[\w|\-]+$/', $data); //not match and output 0 
0
source

All Articles