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, since 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!
对于'\\'字符,你需要写它
'\\'
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, az, AZ 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.