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

4
我希望使用Laravel进行验证,针对一个独特的情况。我要授权的字段是书名。因此它可以包含字母、数字、空格和连字符/下划线/任何其他键。唯一不允许出现的是在输入任何键之前的开头空格。所以书名不能是“ L”,注意空格,而“ L L L”是完全可以接受的。有人能在这种情况下帮助我吗?
到目前为止,我得到了一个正则表达式验证,如下:
regex:[a-z{1}[A-Z]{1}[0-9]{1}]

我不确定如何包含其他限制条件。


Laravel 5.4增加了一个专门用于此目的的中间件Trim Strings Middleware,这是类\Illuminate\Foundation\Http\Middleware\TrimStrings,所以不用担心额外的空格;) - Maraboc
我尝试使用alpha_num作为验证方法,但是当我使用像“LLL”这样的空格时,它会显示错误。 :/ - Muhammad
尝试在您的验证规则中使用此代码:'regex:/^[\w-]*$/' - Maraboc
@Maraboc 没有运气 :/ 它不允许我在中间添加空格。如果我写“LLL”,它会抛出一个错误。 - Muhammad
谢谢@Maraboc,它完美地解决了空格问题!您能告诉我如何允许句点、逗号、反斜杠和括号吗?感谢您的所有帮助。 - Muhammad
显示剩余2条评论
2个回答

7
  • 简短回答:

如果带空格的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:还有一件事,如果您想要一个特殊字符,如\ *或.,您必须像这样转义它们\ *。
对于* ==> 'regex:/^[\s\w-,\*]*$/'

0

检查这个模式:

<?php

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

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

?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接