Jump to content

Detecting illegal characters - need help


Corangar

Recommended Posts

Here is the deal :)

i searched this forum and found a similar topic.

But the script didn't work for me and i dont wanna weak up the ghosts :D

 

if (!preg_match("/[a-z0-9]/i", $username){
   print "Username field has invalid characters!";
   exit;
}

 

Thats a code from "HuggieBear"

The thing is, script works for me in a way that it detects invalid characters but ONLY if all characters are invalid.

If i would insert as username "##$$" it would print "Username field has invalid characters!"

But if i insert "##C2" it would consider it as a valid character cuz of C and 2

 

With other words, i am searching for a script that would detect if it has ANY invalid character anywhere, no matter if valid characters were inserted.

 

Any help would be nice :)

thanks :)

Link to comment
https://forums.phpfreaks.com/topic/41787-detecting-illegal-characters-need-help/
Share on other sites

A slight alteration to the regexp will solve that. You need to tell the regexp engine to require all the characters to be within your ranges provided:

<?php
if (!preg_match("/^[a-z0-9]+\z/i", $username)) {
  // Your username contains invalid characters
}
?>

 

Or, you could simply match for any occurrence of a character not within your range (this may be better):

<?php
if (preg_match('|[^a-z0-9]|i', $username)) {
  // Your username contains invalid characters
}
?>

Do you need to use preg? I guess ereg has is an easier function

 

I guess you could use something like

 

if(ereg("[a-z]|[A-Z]|[0-9]";$var)) {
  //valid
} else {
  //invalid
}

 

That'll look for any alpha-num char and return true if present.

 

Hope I was helpful, and btw, I guess this topic goes on the Regex forum...

 

Regards,

 

Roderick

Do you need to use preg?...I guess you could use something like ...[a-z]|[A-Z]|[0-9]...

 

Per the docs:

Note:  preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().

 

Also, never alternate like that--combine the class: [A-Za-z0-9]

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.