I have been searching for 2 hours now and I still don't get it.
I need to evaluate the input of the account name. That can ONLY contain numbers (0-9
), letters (a-z
and A-Z
) and the dot (.
).
Everything else is forbidden. So, no underscore (_
), plus (+
) and so on.
Valid accounts should look like, e.g.:
john.green
luci.mayer89
admin
I tried many preg_match/regex examples but I don't get it working. Whenever I do echo preg_match(...)
I get 1
as true
.
$accountname = "+_#luke123*";
echo preg_match("/[a-z0-9.]/i", $accountname);
//--> gives back 1 as true
In addition, it would be great to control that the account name starts with at least 2 letters or numbers and ends with at least 1 letter or number - but I am far, far away from that.
You need to use anchors and a quantifier:
echo preg_match("/^[a-z0-9.]+$/i", $accountname);
Your string +_#luke123*
contains a letter and a number, thus there is a match. If we tell the engine to only match the whole string from beginning (^
) to end ($
), we'll make sure this will not match. +
ensures we capture not just 1, but all characters.
See this demo, now there is no match!
EDIT: Since you also need to check these conditions:
string must start with 2 or more letters or numbers and end with 1 or more letters or numbers
I can suggest this ^[a-z0-9]{2,}[a-z0-9.]*[a-z0-9]+$
regex (must be used with i
option) that means:
Another demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With