0

I need to filter out strings that contain anything other than letters, numbers, dots, hyphens, apostrophes or spaces.

Strings with letters, numbers, dots, hyphens and spaces pass the test, but when they contain an apostrophe it fails. (The escape characters on the dot and hyphen don't seem to be making any difference so I put them in just to be sure)

Any thoughts on this?

if (preg_match("/[^a-zA-Z0-9\.\-\'\\s]/", $some_var)){
    echo "Invalid characters";
}
4

2 回答 2

1

由于某些字符的转义(在传递到 preg_match 函数之前,作为字符串的一部分转义),您的答案无法编译。

您可以尝试双重转义:

if (preg_match("/[^a-zA-Z0-9\\.\\-\\'\s]/", $some_var)){ 
    echo "Invalid characters"; 
} 

但不需要转义点、连字符和撇号,因此您可以简化:

if (preg_match("/[^a-zA-Z0-9.'\s-]/", $some_var)){ 
    echo "Invalid characters"; 
} 

请注意,连字符被移到末尾,以免误认为是字符范围。就个人而言,我更喜欢对其进行转义,以防止其他开发人员不小心将新字符添加到列表末尾并导致意外行为。

所以:

if (preg_match("/[^a-zA-Z0-9.\\-'\s]/", $some_var)){ 
    echo "Invalid characters"; 
} 

最后,您可能想要检查您的输入($some_var 变量) - 这实际上是否包含反斜杠,因为 PHP 有时会添加它(例如,用户键入“can't”,但作为“can\'t”发送 -你可能需要stripslashes先)。

例如。

if (preg_match("/[^a-zA-Z0-9.\\-'\s]/", stripslashes($some_var))){ 
    echo "Invalid characters"; 
} 
于 2012-06-20T09:28:19.537 回答
0

尝试这个:

if (preg_match("/[^a-zA-Z0-9.'\s-]/", $some_var)){
      echo "Invalid characters";
}
于 2012-06-20T09:17:12.037 回答