2012-04-07 136 views
2

我想使用preg_match來匹配數字1 - 21.我怎樣才能使用preg_match做到這一點?如果數字大於21,我不想匹配任何東西。PHP preg_match範圍

example preg_match('([0-9][0-1]{0,2})', 'Johnathan 21'); 
+4

我不認爲你需要限制正則表達式的有效解決方案,其他方法(例如捕獲正則表達式中的[[0-9] {1,2}'並且之後驗證)可能更容易。 http://blogs.msdn.com/b/oldnewthing/archive/2006/05/22/603788.aspx – DCoder 2012-04-07 17:10:29

+0

@二極管:這應該是一個答案。 – 2012-04-07 17:17:24

+0

是的。我認爲我會更簡單地使用正則表達式。 – James 2012-04-07 17:21:26

回答

2

comment above複製:

我建議匹配只是([0-9]{1,2})(也許裹着\b,基於輸入格式)並過濾數值後來,在PHP代碼中。請參閱Raymond Chen's thoughts on the subject

+0

謝謝。我用'\ d +'將數字匹配到數組中,然後我驗證它是在1 - 21之間。 – James 2012-04-07 17:25:24

1

從字面上看:

preg_match('~ (1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21)$~', 'Johnathan 21'); 

但也許這是更漂亮:

preg_match('~ ([1-9]|1[0-9]|2[01])$~', 'Johnathan 21'); 
+0

這個例子將匹配每個數字。 – James 2012-04-07 17:05:00

+0

哪一個?爲了什麼?我應該讓它變得貪婪嗎? – hakre 2012-04-07 17:05:55

+0

是的。我想使這個貪婪。 – James 2012-04-07 17:08:02