添加锚点时为什么这个正则表达式失败了?

This is a match:

preg_match('/[a-bA-B0-9]+/', 'username')

But this is not:

preg_match('/^[a-bA-B0-9]+$/', 'username')

Why is that?

Are you testing the actual literal 'username'?

/[a-bA-B0-9]+/ will test the existence of a,b,A,B,0,1,2,3,4,5,6,7,8,9 anywhere in the string. So it will match abBa854Abba32, and it will match sjfsgfafnvesv.

/^[a-bA-B0-9]+$/ will test that the enitre string is made of a,b,A,B,0,1,2,3,4,5,6,7,8,9. So it will match abBa854Abba32, and it will not match sjfsgfafnvesv.

Perhaps you meant /^[a-zA-Z0-9]+$/.

The second does not match because you have told the regex to match a sequence that starts with one of those items in the character class. The first letter of your string is "u", and there is no "u" in your character class [a-bA-B0-9].

From here

You can see that it only matches a:

Results

1 match was found:

Array ( [0] => a )