2017-07-27 63 views
1

我想驗證使用Laravel的獨特情況。我正在授權的領域是一本書的名稱。所以它可以有字母字符,數字字符,空格,和超/下劃線/任何其他鍵。我不想讓它擁有的唯一的東西是在開始輸入任何鍵之前的空格。所以這個名字不能是「L」,注意這個空間,而「L L L」是完全可以接受的。任何人都可以幫助我在這種情況下?使用正則表達式來允許使用字母,超字母,下劃線,空格和數字

到目前爲止,我得到了一個正則表達式驗證這樣:

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

我不確定如何包含其他限制。

+0

Laravel 5.4增加了一箇中間件只是爲了這一目的'修整字符串Middleware'這裏是類'\照亮\基金會\ HTTP \中間件\ TrimStrings'所以不用擔心關節外空格;) – Maraboc

+0

是啊,我試圖使用alpha_num作爲驗證方法,但是當我使用空格如「LLL」時,它說有錯誤。 :/ – Muhammad

+0

嘗試在你的驗證規則中使用''正則表達式:/^[\ w - ] * $ /''! – Maraboc

回答

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-,\*]*$/'

0

檢查這種模式:

<?php 

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

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

?> 
相關問題