How to use preg_match in php?

11,601

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.).

Share:
11,601
mohammad talaie
Author by

mohammad talaie

Updated on June 29, 2022

Comments

  • mohammad talaie
    mohammad talaie almost 2 years

    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?