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)) {
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.
source share