Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate that string contains only numbers, letters, and underscores

Tags:

validation

php

How do you check if a string contains invalid characters?

I want to restrict each user's username with PHP to having numbers, letters, and underscores.

like image 759
blah Avatar asked Jan 20 '26 15:01

blah


1 Answers

You can use a regular expression:

if (preg_match("^[0-9A-Za-z_]+$", username) == 0) {
    echo "<p>Invalid username</p>";
}
like image 90
Dean Harding Avatar answered Jan 22 '26 03:01

Dean Harding



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!