Php preg_match only numbers, letters and dots

I've searched for 2 hours and I still don't get it. I need to evaluate entering an account name. It can ONLY contain numbers ( 0-9

), letters ( a-z

and a-z

) and period ( .

).

Anything else is prohibited. So underscore ( _

), plus ( +

), etc.

Valid accounts should look like:

john.green
luci.mayer89
admin

      

I have tried many preg_match / regex examples but I am not working. Whenever I do echo preg_match(...)

, I get 1

like true

.

$accountname = "+_#luke123*";
echo preg_match("/[a-z0-9.]/i", $accountname);

//--> gives back 1 as true

      

Also, 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'm far, far away from that.

+3


source to share


1 answer


You need to use bindings and quantifier:

echo preg_match("/^[a-z0-9.]+$/i", $accountname);

      

Your string +_#luke123*

contains a letter and a number, so there is a match. If we tell the engine to match the entire chain from start ( ^

) to end ( $

), we will make sure it doesn't match. +

captures not only 1, but all characters.

See this demo , now there is no match!

EDIT : Since you also need to check these conditions:



Line

must start with two or more letters or numbers and end with 1 or more letters or numbers

I can suggest this regex ^[a-z0-9]{2,}[a-z0-9.]*[a-z0-9]+$

(should be used with option i

) which means:

  • Starts with two or more letters or numbers.
  • then do any number of numbers, letters or periods
  • and ends with 1 or more letters or numbers.

Another demo

+5


source







All Articles