I'm fairly new to PHP, and I'm setting up a "members area" for my site following this tutorial. There seems to be a problem with the code near the bottom of the page.
When trying to pick out the invalid characters from a username field, the array $junk is set up.
$junk = array('.' , ',' , '/' , '\' , '`' , ';' , '[' , ']' , '-', '_', '*', '&', '^',
'%', '$', '#', '@', '!', '~', '+', '(', ')', '|', '{', '}', '<', '>', '?', ':', '"', '=');
This block of code returns a syntax error for me.
Now, my first thought was that either the '#' or the '(' and ')' was causing the problem, sin开发者_如何学编程ce they are commonly used in html and php. The error was still returned with them removed.
I am new to php, so it very well could be just some small syntax error I am missing. Any input would be great. Thanks!
EDIT: Also, if there is an easier way of doing this, please let me know!
For '\' character you need to write it like
'\\'
The backslash needs to be escaped: '\\'
. That's because \'
gives you a literal apostrophe, which you couldn't otherwise get inside a singly quoted string.
There is a much easier way to do this, regular expressions. If you want to set up the username to only accept alpha-numeric characters it's,
$user = preg_replace("/[^0-9a-zA-Z]+/", "", $user);
The expression essentially says, replace anything that is not 0-9, a-z, A-Z with "". If you want to allow the "@", "." (period) and "-" and "_" symbols:
$user = preg_replace("/[^0-9a-zA-Z\@\.\-\_]+/", "", $user);
Regular expressions are a very powerful tool. They can be used in most languages, including javascript and PHP. So it is worth taking the time to learn them.
for a smaller array, make a string and then call str_split to get it as an array of chars.
$junk = str_split('.,/\\`;[]-_*&^%S#@!~+()|{}<>?:"=')
Personally I would have used the chars in the following order
~`!@#$%^&*()-_+={}[]\|;:'",.<>/?
Since that is how they are on my keyboard. But that's just a minor issue. I knows the ' (single quote) is missing from the original string.
Better ways to validate input involve regular expressions.
精彩评论