just a quick question am abit rubish with regex so thought I would post on here. The regex below is to validate a username.
Must be between 4-26 characters long
Start with atleast 2 letters
I have this so far, but isn't working
<?php
$username=$_POST['username'];
if (!eregi("^([a-zA-Z][0-9_.]){4,26}$",$username))
{
return false;
}
else
{
echo "username ok";
}
?>
Thanks :)
To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.
In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.
The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. The preg_match_all() function matches all occurrences of pattern in string.
You could use the regex
/^(?=[a-z]{2})(?=.{4,26})(?=[^.]*\.?[^.]*$)(?=[^_]*_?[^_]*$)[\w.]+$/iD
as in
<?php
$username=$_POST['username'];
if (!preg_match('/^(?=[a-z]{2})(?=.{4,26})(?=[^.]*\.?[^.]*$)(?=[^_]*_?[^_]*$)[\w.]+$/iD',
$username))
{
return false;
}
else
{
echo "username ok";
}
?>
^(?=[a-z]{2})
ensure the string "Start with atleast 2 letters".(?=.{4,26})
ensure it "Must be between 4-26 characters long".(?=[^.]*\.?[^.]*$)
ensures the following characters contains at most one .
until the end.(?=[^_]*_?[^_]*$)
ensures at most one _
.[\w.]+$
commits the match. It also ensures only alphanumerics, _
and .
will be involved.(Note: this regex assumes hello_world
is a valid user name.)
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