سؤال

I'm using this regular expression to test if a username is valid:

[A-Za-z0-9 _]{3,12} when I test it for matches in a text editor with the string test'ing, it highlights 'test' and 'ing', but when I use the following code in PHP:

if(!preg_match('/[A-Za-z0-9 _]{3,12}/', $content) where $content is test'ing and it should return FALSE, it still returns true.

Is there something wrong with my regular expression? I need:

  • Minimum length 3, max 12 {3,12}
  • No spaces/underscores in front or after the string, and no spaces/underscores in a row anywhere (I'm using additional checks for this because I'm not very good with regex)
  • Only alphanumerics, spaces and underscores allowed [A-Za-z0-9 _]

Thanks in advance...

هل كانت مفيدة؟

المحلول

You're missing the anchors in the regular expression, so the regex can comfortably match 3 characters in the character class anywhere in the string. This is not what you want. You want to check if your regex matches against the entire string. For that, you need to include the anchors (^ and $).

if(!preg_match('/^[A-Za-z0-9 _]{3,12}$/', $content)
                 ^                   ^

^ asserts the position at the beginning of the string and $ asserts position at the end of the string. It's important to note that these meta characters do not actually consume characters. They're zero-width assertions.

Further reading:

نصائح أخرى

You should add start and end anchors (^$):

if(!preg_match('/^[A-Za-z0-9 _]{3,12}$/', $content)

The anchor ^ matches the start of the string and $ matches the end. That way, it will only match if the whole string satisfies your regex.

Hope that helps

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top