Forum Moderators: coopster
I know I'm going to have to use regular expressions for this. I can probably figure out the exact regex to use, too. But my problem is how to check the string to see if it contains any of the conditions in the regex. What function would I use? And, I hate to ask, but what do I need to do to my regex so it will "trigger" if one of the illegal characters is found, given that they could come up at any point in the string?
Basically I'm having a mental block. I'm sure I've done this before but I can't remember how. Any pointers, references, tips, etc. will be appreciated.
Thanks,
Matthew
function badchars($string)
{
if (preg_match("/[^0-9a-z\.\&\@]/i", $string)) {
exit('I found a bad character in ' . $string);
}
}
badchars('example');
badchars('EXAMPLE');
badchars('Example*');
[b]![/b]preg_match... would have been necessary, as in the data does not meet our standards, so do such-and-such. So just what is this doing? Also, perl regular expressions are entirely new to me. I know a little about the "other" kind of regex (non-perl, can't remember the name right now) but not much. So I'm having a hard time understanding your syntax. Could you explain a bit of what's going on there? I've read around the Internet some, but haven't really found a guide that started where I am - at the beginning! ;)
One more thing: how can I add characters that are allowed? For instance, some of my fields will be allowed to have periods and commas; how can I add these to the list of permitted characters?
Thanks again,
Matthew
Either will get you the results. (I prefer preg_match/!preg_match, because then I know my defined characters are always positive, and I can see positive/negative at the beginning of the expression (easier for me to read quickly), but that is personal preference.)
Justin
if (preg_match("/[^0-9a-z\.\&\@]/i", $string)) { POSIX is the other engine you are thinking of. Sorry for the switchup on you here, I always use the PCRE [php.net] (Perl Compatible Regular Expressions) as they are binary-safe and usually always faster.
To add more acceptable characters you simply add them to the rest of the class. Periods are already included, so now we'll add the comma and this time I won't escape the characters that I am certain do not have any other special meaning just to show that it works with or without escaping characters that don't have a special meaning:
if (preg_match("/[^0-9a-z\.&@,]/i", $string)) {