Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use preg_match in php? [closed]

I want to create a form validation and I want to make sure that users won't enter any dangerous codes in the textboxes so I want to use preg_match to do that. What I don't like users to type is (something instead of words from a-z , words from A-Z and numbers). Now how can I use preg_match here?

like image 728
Mohammadali Talaie Avatar asked Jan 18 '26 20:01

Mohammadali Talaie


1 Answers

This regex will only allow letters and numbers.

/^[A-Z\d]+$/i

used in preg_match

if(preg_match('/^[A-Z\d]+$/i', $string)) {
      echo 'Good';
} else {
     echo 'Bad';
}

Regex101 demo: https://regex101.com/r/wH4uQ3/1

The ^ and $ require the whole string match (they are anchors). The [] is a character class meaning any character inside is allowed. The + means one or more of the preceding character/group (this is known as a quantifier). The A-Z is a range that the character class understands to be letters a-z. \d is a number. The /s are delimiters telling where the regex starts and ends. The i is a modifier making the regex case insensitive (could remove that and add a-z so lowercase letters are allowed as well).

PHP Demo: https://eval.in/486282

Note PHP demo fails because whitespace isn't allowed. To allow white space add \h or \s in the character class (the s includes \h so no need for both; \h is for horizontal spaces.).

like image 76
chris85 Avatar answered Jan 20 '26 11:01

chris85