pretty standard regex required please

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

pretty standard regex required please

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

[a-zA-Z0-9_-]
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

lol, didnt think regex strings could look that simple 8O
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

<-- really needs to learn regex
Post Reply