Page 1 of 1

pretty standard regex required please

Posted: Fri Apr 14, 2006 10:36 am
by malcolmboston
have got a clue about regex so need a hand,

what would the regex string look like if i wanted to match this:

a-z, A-Z, 0-9, - and _

thanks

Posted: Fri Apr 14, 2006 10:38 am
by feyd

Code: Select all

[a-zA-Z0-9_-]

Posted: Fri Apr 14, 2006 10:42 am
by malcolmboston
lol, didnt think regex strings could look that simple 8O

Posted: Fri Apr 14, 2006 11:13 am
by malcolmboston
this code..

Code: Select all

function checkUsernameAllowed ($username) {
	$start = getMicrotime();
	// firstly check its in the correct format
	$regex = "[a-zA-Z0-9_-]";
	if (ereg ($regex, $username)) {
		$end = getMicrotime();
		print "Username: {$username}\nvalid";
	} else {
		$end = getMicrotime();
		print "Username: {$username}\ninvalid";
	}
	$total = number_format(($end - $start), 4);
	print "\n{$total} to analyze for validity\n\n";
}

checkUsernameAllowed ("malcolmboston");
checkUsernameAllowed ("malcolm!!!");

?>
returns

Code: Select all

Username: malcolmboston
valid
0.0003 to analyze for validity

Username: malcolm!!!
valid
0.0001 to analyze for validity
obviously, malcolm!!! should fail

Posted: Fri Apr 14, 2006 11:24 am
by feyd
No, it shouldn't. Why? The regex only looks for a single character match. If any character in the tested string match, the regex will say it found it.

Code: Select all

if (preg_match('#^[a-zA-Z0-9_-]+$#', $username))
will perform it over the entire string.

Posted: Fri Apr 14, 2006 11:26 am
by malcolmboston
<-- really needs to learn regex