Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match only numbers, letters and dot

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.

like image 932
Lox Avatar asked Mar 17 '23 06:03

Lox


1 Answers

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:

  • Starts with 2 or more letters or numbers
  • then follow any number of digits, letters or periods
  • and ends in 1 or more letters or numbers.

Another demo

like image 198
Wiktor Stribiżew Avatar answered Mar 23 '23 02:03

Wiktor Stribiżew