2011-07-20 53 views
2

我一直在試圖檢查一個字符串值是否以一個數值或空格開始,並相應地採取行動,但它似乎沒有工作。這裏是我的代碼:PHP:正則表達式匹配字符串前面沒有數字或空格

private static function ParseGamertag($gamertag) 
{ 

    $safetag = preg_replace("/[^a-zA-Z0-9\s]+/", "", $gamertag); // Remove all illegal characters : works 
    $safetag = preg_replace("/[\s]+/", "\s", $safetag); // Replace all 1 or more space characters with only 1 space : works 
    $safetag = preg_replace("/\s/", "%20", $safetag); // Encode the space characters : works 

    if (preg_match("/[^\d\s][a-zA-Z0-9\s]*/", $safetag)) // Match a string that does not start with numerical value : not working 
     return ($safetag); 
    else 
     return (null); 

} 

所以hiphop112是有效的,但112hiphip無效。 0down無效。

第一個字符必須是英文字母[a-zA-Z]

任何幫助,非常感謝。

回答

4

您需要將您的pa ttern到字符串的開頭使用錨^

preg_match("/^[^\d\s][a-zA-Z0-9\s]*/", $safetag) 

否則你的正則表達式會找到一個有效的匹配某處字符串中

你可以找到錨的解釋here on regular-expressions.info

注意不同的含義的^。在字符類外部,它是字符串開頭的錨點,在第一個位置的字符類內部是類的否定。

+0

謝謝你,偉大的解釋。 –

3

嘗試添加^來表示字符串的開始......

preg_match("/^[^\d\s][a-zA-Z0-9\s]*/", $safetag) 

還,如果第一個字符必須是字母,這可能會更好:

preg_match("/^[a-zA-Z][a-zA-Z0-9\s]*/", $safetag) 
1

添加在正則表達式開始處的「開始於胡蘿蔔」:

/^[^\d\s][a-zA-Z0-9\s]*/ 
0
preg_match("/^[a-zA-Z]+[a-zA-Z0-9\s]*/", $safetag)) 
2

使用^紀念字符串的開頭(雖然^[ ]意味着)。

您還可以使用\w代替a-zA-Z0-9

/^[^\d\s][\w\s]*/ 
1

的第一件事情,什麼也不會匹配\ S因爲你已經通過替換爲%20的所有空間。

爲什麼不匹配正:

[a-zA-Z][a-zA-Z0-9\s]* 
相關問題