Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are backslashes matched by character classes not containing them in Regular Expressions?

I am trying to match an alphanumeric String in PHP 8.2 using preg_match.

$str = '\\\\';

echo preg_match("/^[A-z0-9]*$/", $str);

The output of the following code is 1, indicating that the pattern matches the subject.
How is it possible, that the character class [A-z0-9] matches the backslashes, which are not contained in it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your regex contains A-z which means any any character between 65 and 122 (ascii table). \ is 92 which falls within that range. A tool like regex101 can help clarify what is included in regexes

To fix update the regex to be /^[A-Za-z0-9]*$/ which specifies only letters or numbers

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading