Search code examples
regexshorthandcharacter-class

php preg_match using shorthand and character class combined


echo preg_match( '/\d[A-Z]/', 'CD' ); // Displays “0”

How can it display 0 when clearly there are characters that match the range "[A-Z]"?

Is it the way the parsing occurs?


Solution

  • The regex /\d[A-Z]/ says that the input must have a digit first, and then an alphabet must be present.
    Since the input CD doesnot contain a digit and an alphabet following it, the function returns 0.

    To match more than one capital letters or digits, you can use the following regex.

    /[\dA-Z]+/