在PHP中只允许某些字符

时间:2022-01-01 11:00:17

I need to check to see if a variable contains anything OTHER than a-z A-Z 0-9 and the "." character (full stop). Any help would be appreciated.

我需要检查一个变量是否包含除a-z a-z 0-9和“。”字符(句号)之外的其他内容。如有任何帮助,我们将不胜感激。

3 个解决方案

#1


8  

if (preg_match('/[^A-Z\d.]/i', $var))
  print $var;

#2


10  

There are two ways of doing it.

有两种方法。

Tell whether the variable contains any one character not in the allowed ranges. This is achieved by using a negative character class [^...]:

告诉变量是否包含在允许范围之外的任何一个字符。这是通过使用一个负面角色类[^…]:

preg_match('/[^a-zA-Z0-9\.]/', $your_variable);

Th other alternative is to make sure that every character in the string is in the allowed range:

另一种选择是确保字符串中的每个字符都在允许的范围内:

!preg_match('/^[a-zA-Z0-9\.]*$/', $your_variable);

#3


7  

if (preg_match("/[^A-Za-z0-9.]/", $myVar)) {
   // make something
}

The key point here is to use "^" in the [] group - it matches every character except the ones inside brackets.

这里的关键点是使用“^”[],它匹配除了括号里面的每个角色。

#1


8  

if (preg_match('/[^A-Z\d.]/i', $var))
  print $var;

#2


10  

There are two ways of doing it.

有两种方法。

Tell whether the variable contains any one character not in the allowed ranges. This is achieved by using a negative character class [^...]:

告诉变量是否包含在允许范围之外的任何一个字符。这是通过使用一个负面角色类[^…]:

preg_match('/[^a-zA-Z0-9\.]/', $your_variable);

Th other alternative is to make sure that every character in the string is in the allowed range:

另一种选择是确保字符串中的每个字符都在允许的范围内:

!preg_match('/^[a-zA-Z0-9\.]*$/', $your_variable);

#3


7  

if (preg_match("/[^A-Za-z0-9.]/", $myVar)) {
   // make something
}

The key point here is to use "^" in the [] group - it matches every character except the ones inside brackets.

这里的关键点是使用“^”[],它匹配除了括号里面的每个角色。