Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question about Regex in preg_match

Status
Not open for further replies.

SetoKaiba

Programmer
Jun 16, 2004
28
0
0
US
I'm trying to write a preg_match function that matches invalid characters in an input (in this case, a username). Here is the function:

if ( preg_match('/[^A-Za-z0-9]/', $username) ) { error; }
Based on the regex, the if-statement should return true when it matches a character other than A-Z, a-z and 0-9 meaning that it found at least one match of an invalid character.

However, when I set $username equal to "ABCD&" or "ABCD+" excluding quotes, the if-statement never becomes true (no matches found), when it should match the & and + characters. Of course, "ABCD" also will not yield and error.

I am unsure of what the error is, but I presume I am missing a flag. The input comes from $_POST, and I do not apply any functions (such as addslashes or htmlspecialchars) to the input when I run that if-statement on it.
 
I can't duplicate your script's behavior. With an HTML file that reads:

Code:
<html>
	<body>
		<form method="post" action="test_foo.php">
			<input type="text" name="foo">
			<input type="submit">
		</form>
	</body>
</html>

and a PHP script that reads:

Code:
<?php
if ( preg_match('/[^A-Za-z0-9]/', $_POST['foo']) )
{
	print "no good";
}
else
{
	print "good";
}

?>

I get "good" for "ABCD" and "no good" for "ABCD&" and "ABCD+"



Want the best answers? Ask the best questions! TANSTAAFL!
 
I'm a dumdum, I should have just forced input. I didn't think my scripts were physically changing input, as for some reason the + and & characters are being converted to whitespace. I'll have to look into it more.

Out of curiosity, do you have to escape the '-' character in '/[^A-Za-z0-9]/'?

ie. '/[^A-Za-z0-9/-]/' or '/[^A-Za-z0-9-]/'
 
Ignore last post. If I could edit posts here I would have.

-> Turns out it was indeed the input being messed with. I was using an AJAX script to pass the username to the server, and I was using encodeURI and not encodeURIcomponent which seems to have fixed the bug. Thanks for your help sleipnir214, woke me up more than anything.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top