Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regex validation

Tags:

regex

php

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

  • Can only contain numbers and one underscore and one dot

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 :)

like image 617
Elliott Avatar asked Sep 19 '10 20:09

Elliott


People also ask

How do you validate expressions in regex?

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.

Does PHP support regex?

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.

What is the purpose of Preg_match () regular expression in PHP?

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.


1 Answers

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";
}

?>
  • The ^(?=[a-z]{2}) ensure the string "Start with atleast 2 letters".
  • The (?=.{4,26}) ensure it "Must be between 4-26 characters long".
  • The (?=[^.]*\.?[^.]*$) ensures the following characters contains at most one . until the end.
  • Similarly (?=[^_]*_?[^_]*$) ensures at most one _.
  • The [\w.]+$ commits the match. It also ensures only alphanumerics, _ and . will be involved.

(Note: this regex assumes hello_world is a valid user name.)

like image 72
kennytm Avatar answered Sep 26 '22 02:09

kennytm