简体   繁体   English

尝试设置无效字符数组时出现语法错误

[英]Syntax error trying to set up invalid character array

I'm fairly new to PHP, and I'm setting up a "members area" for my site following this tutorial . 我是PHP的新手,我在本教程之后为我的网站设置了“成员区”。 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。

$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. 现在,我的第一个想法是'#'或'('和')'引起了问题,因为它们通常用于html和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. 我是php的新手,所以它很可能只是我遗漏的一些小语​​法错误。 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); $ user = preg_replace(“/ [^ 0-9a-zA-Z] + /”,“”,$ user);

The expression essentially says, replace anything that is not 0-9, az, AZ with "". 表达式基本上是说,用“”替换不是0-9,az,AZ的任何东西。 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. 它们可以在大多数语言中使用,包括javascript和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. 对于较小的数组,创建一个字符串,然后调用str_split将其作为字符数组。

$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. 验证输入的更好方法涉及正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM