我有一个模式,我想允许字母数字以及 space 尤其是 SPACE

I have a pattern where i want to allow alphanumeric and also space especially SPACE

我已经尝试了很多东西,比如 \n 和 [[:space:]] 但我不知道我应该把它放在哪里。

这里有一些代码:

 $sPattern = '/^([-_@a-zA-Z0-9])+$/';

提前致谢

我仍然想知道问题出在哪里,但让我稍微解释一下:POSIX 字符 classes(如 [:space:])只能在常规的普通 字符 classes 中使用(如 [a-z])。当您单独使用它们时,它们看起来像 [[:space:]]+。但是当你将它们与其他范围一起使用时,它们看起来像 [a-z[:space:]].

现在,您不需要 PHP PCRE 正则表达式中的 [:space:],您可以使用 shorthand 字符 class \s.

此外,\w 匹配 [a-zA-Z0-9_] 除非 您添加 /u 修饰符),因此您可以进一步缩短您的模式:

$sPattern = '/^[-@\w\s]+$/';

此外,+ 必须放在右方括号旁边,以减少正则表达式引擎捕获功能的开销。 (...) 是多余的,因为您可以使用组 0 值访问整个匹配项。

注意: [:space:] != \s in PHP (see reference).

The space characters are HT (9), LF (10), VT (11), FF (12), CR (13), and (32). Notice that this list includes the VT character (code 11). This makes [:space]: different to \s, which does not include VT (for Perl compatibility).

如果需要匹配VT,使用$sPattern = '/^[-@\w[:space:]]+$/';.

这显然是电脑的问题所以我用了别的东西:

    $sPattern = "/^([-_@\w\f])+$/";

    $value = str_replace(' ', '', $value);