Jump to content

[SOLVED] problem with regular expressions


Errant_Shadow

Recommended Posts

I'm trying to use regular expressions to validate user name in my registration form.

I want to limit user names to only alpha numeric characters and spaces, dashes, and underscores.

 

This is what I'm using:

124				// test name against regular expression
125				if(eregi("^[a-zA-Z-0-9_- ]{4,20}$ ", $testName)){
126					// query database for $testName
...					
140				// else, if test name failed against regular expressions
141				} else {
142					$userError = '<p>The user name "'.$_POST['myName'].'" is invalid.</p>';
143					
144				} // end if(eregi("^[a-zA-Z-0-9_- ]{4,20}$ ", $testName))

 

but when I run it, it gives me the error

"Warning: eregi() [function.eregi]: REG_ERANGE in /home/ekuplu/public_html/gmStudios/index.php on line 125"

 

what am I doing wrong here?

Link to comment
https://forums.phpfreaks.com/topic/144188-solved-problem-with-regular-expressions/
Share on other sites

always put the - (hyphen, dash, whatever) at the END of the expression set; You also have an extra hyphen between the A-Z and 0-9 parts, you dont need one there. or want one there.

 

Fixed Expression:

eregi("^[a-zA-Z0-9_ -]{4,20}$ ", $testName)

 

Also, i would use preg_match (i think its faster lol).

 

// i = Case-INsensitive, matches A-Z as well as a-z. \A = Start of subect, regardless of multiline mode.

 

preg_match("/\A[a-z0-9 _-]{4,20}$/i",$testName);

 

 

Hope it helps :P

 

PS: Preg_Match expressions require you wrap the REGEXP i forward slashes, or another compatible sybmol, these are the start and end of the expression, there are "modifiers" that are put on the end of the expression, liek the "i" above which makes the match, case-insensitive. Though modifiers are not required, the forward slashes are.

\A is the same as ^,

 

Thge difference is ^ is like "At the start of this line".

\A is like "At the very start of $subject".

 

So if your matching against a multilined string, eg:

 

this is [illegal ch4rs]

a multiline

blah blah

 

so if u used ^, it would match ok since it would match line 2 and 3, but obviousl you dot see line 1.

 

if you used \A, it would fail, since it spotted illegal characters o the first line. (it interprets it as a single lie, rather than multiline.)

 

php.net/pcre for more information.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.