为什么这个正则表达式匹配正面?
Given the pattern ^[a-zA-Z0-9 .\-_]+$
and the string te\\st
, why is the match positive? I'm using this to validate usernames and I don't want people to put slashes in their usernames, it messes with URLs.
I'm calling ereg($pattern, $username)
, running PHP version 5.2.8.
给定模式 我正在调用 ^ [a-zA-Z0-9。\ -_] + $ 代码>和字符串
te \\ st code>,为什么匹配正面? 我正在使用它来验证用户名,我不希望人们在他们的用户名中加入斜杠,它会混淆URL。 p>
ereg($ pattern, $ username) code>,运行PHP版本5.2.8。 p>
div>
ereg
is crazy. I recommend avoiding it. You should try using preg_match
for this:
$count = preg_match('/^[a-zA-Z0-9 .\-_]+$/', 'te/\st', $matches);
print_r($matches); // empty array (no matches)
print $count; // 0 (no matches)
^[a-zA-Z0-9 ._-]+$
Will work as well. To match a literal - in a character class it is usually safest to place it right before the ending ], or right after the opening [ when using ereg (POSIX). You should be able to escape out the - but for some reason when escaping it directly after the . seems to fail. Anyway there is a solution if you must use ereg. Really good question as to why that fails, the . should just be a normal character within the character class. Ereg is buggy.
And if you have the choice use preg (PCRE)...