使用正则表达式允许字母字符、连字符、下划线、空格和数字

Use regex to allow for alphabetic characters, hypens, underscores, spaces, and numbers

我想针对特定情况使用 Laravel 进行验证。我授权的字段是一本书的名字。所以它可以有字母字符、数字字符、spaces 和 hypens/underscores/any 其他键。我唯一不希望它有的是开头的 spaces,在你输入任何键之前。所以名称不能是“L”,注意 space,而 "L L L" 是完全可以接受的。在这种情况下有人可以帮助我吗?

到目前为止,我得到了这样的正则表达式验证:

regex:[a-z{1}[A-Z]{1}[0-9]{1}]

我不确定如何添加其他限制。

检查此模式:

<?php

$pattern = '/^(?=[^ ])[A-Za-z0-9-_ ]+$/';
$test = ' L';

if (preg_match($pattern, $test)) {
    echo 'matched';
} else {
     echo 'does not match';   
}

?>
  • 简答:

对于带空格的 alpha_num 使用此正则表达式:

'regex:/^[\s\w-]*$/'
  • 长一点:)

这里是正则表达式的一些定义块:

^           ==>  The circumflex symbol marks the beginning of a pattern, although in some cases it can be omitted
$           ==>  Same as with the circumflex symbol, the dollar sign marks the end of a search pattern
.           ==>  The period matches any single character
?           ==>  It will match the preceding pattern zero or one times
+           ==>  It will match the preceding pattern one or more times
*           ==>  It will match the preceding pattern zero or more times
|           ==>  Boolean OR
–           ==>  Matches a range of elements
()          ==>  Groups a different pattern elements together
[]          ==>  Matches any single character between the square brackets
{min, max}  ==>  It is used to match exact character counts
\d          ==>  Matches any single digit
\D          ==>  Matches any single non digit character
\w          ==>  Matches any alpha numeric character including underscore (_)
\W          ==>  Matches any non alpha numeric character excluding the underscore character
\s          ==>  Matches whitespace character

如果你想添加一些其他字符,你应该做的就是将它添加到 [] 块。

例如,如果您想要允许 , ==> 'regex:/^[\s\w-,]*$/'.

PS :如果您想要一个 setial 字符,例如 \ * 或 .你必须像这样逃避它们 \ * .

对于* ==> 'regex:/^[\s\w-,\*]*$/'