PHP - preg_match()

筅森魡賤 提交于 2019-12-04 10:17:02

You just need a quantifier in your regex:

Zero or more characters *:

/^[a-zA-Z0-9]*$/

One or more characters +:

/^[a-zA-Z0-9]+$/

Your regex as is will only match a string with exactly one character that is either a letter or number. You want one of the above options for zero or more or one or more, depending on if you want to allow or reject the empty string.

Your regular expression needs to be changed to

/^[a-zA-Z0-9]{1,8}$/

For usernames between 1 and 8 characters. Just adjust the 8 to the appropriate number and perhaps the 1.

Currently your expression matches one character

Please keep in mid that preg_match() and other preg_*() functions aren't reliable because they return either 0 or false on fail, so a simple if won't throw on error.

Consider using T-Regx:

if (pattern(('^[a-zA-Z0-9]{1,8}$')->matches($input)) 
{
    // Matches! :)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!