使用正则表达式来允许使用字母,超字母,下划线,空格和数字
问题描述:
我想验证使用Laravel的独特情况。我正在授权的领域是一本书的名称。所以它可以有字母字符,数字字符,空格,和超/下划线/任何其他键。我不想让它拥有的唯一的东西是在开始输入任何键之前的空格。所以这个名字不能是“L”,注意这个空间,而“L L L”是完全可以接受的。任何人都可以帮助我在这种情况下?使用正则表达式来允许使用字母,超字母,下划线,空格和数字
到目前为止,我得到了一个正则表达式验证这样:
regex:[a-z{1}[A-Z]{1}[0-9]{1}]
我不确定如何包含其他限制。
答
- 简短的回答:
对于空间alpha_num使用这个表达式:
'regex:/^[\s\w-]*$/'
- 时间长一点的:)
下面是一些定义的regex的bolcks:
^ ==> 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 caharcter
\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 char这样我们*或*。你必须像这样\ *。
对于*
==>'regex:/^[\s\w-,\*]*$/'
答
检查这种模式:
<?php
$pattern = '/^(?=[^ ])[A-Za-z0-9-_ ]+$/';
$test = ' L';
if (preg_match($pattern, $test)) {
echo 'matched';
} else {
echo 'does not match';
}
?>
Laravel 5.4增加了一个中间件只是为了这一目的'修整字符串Middleware'这里是类'\照亮\基金会\ HTTP \中间件\ TrimStrings'所以不用担心关节外空格;) – Maraboc
是啊,我试图使用alpha_num作为验证方法,但是当我使用空格如“LLL”时,它说有错误。 :/ – Muhammad
尝试在你的验证规则中使用''正则表达式:/^[\ w - ] * $ /''! – Maraboc