[英]Help with a regular expression in php
我正在嘗試使以下正則表達式模式適用於以下條件。 對於 20 世紀和 21 世紀,允許的值為 1978 年或 1978-1979 年,2010-2011 年也是如此。 此外,如果像 1978-1979 一樣是 2 年,它們只能相隔一年。
我已經完成了以下內容,它接受 4 位數字 /^[1-9]{4}$/ 這是非常基本的。 但任何幫助將不勝感激!
做到這一點的唯一方法是分兩步。 首先,您需要使用正則表達式來提取 2 個日期,然后您需要驗證是否有 2 個日期,它們相隔 1 年。
解決方案:
<?php
preg_match('/^((?:19|20)\d{2})(?:-((?:19|20)\d{2}))$/', '1898-1899', $matches);
// Validate a date range
if ( ! empty($matches[2]) && intval($matches[2]) - intval($matches[1]) != 1 )
die('Invalid date range');
if ( empty($matches[1]) )
die('Invalid date');
您可以使用正則表達式確保每一年都是從 1900 年到 2099 年,但您需要使用程序邏輯來驗證第二年(可選)是否大於第一年。 這是一個經過測試的 function(帶有注釋的正則表達式)來驗證年份(或年份范圍):
function validYear($yearfield) {
if (preg_match('/
# Match a 20th or 21st century year (or range of years).
^ # Anchor to start of string.
( # $1: Required year.
(?:19|20) # Century is 19 or 20.
[0-9]{2} # Year is 00 to 99.
) # End $1: start year.
(?: # Group for optional range part.
- # Range part requires - separator.
( # $2: Range ending year.
(?:19|20) # Century is 19 or 20.
[0-9]{2} # Year is 00 to 99.
) # End $2: Range ending year.
)? # Range part is optional.
$ # Anchor to end of string.
/x', $yearfield, $matches))
{
$year1 = (int)$matches[1];
$year2 = isset($matches[2]) ? (int)$matches[2] : $year1 + 1;
if ($year2 > $year1) return true;
}
return false;
}
我不認為這真的是正則表達式的最佳用途,但我喜歡挑戰。
所以只是為了表明在正則表達式http://regexr.com?2u843中一切皆有可能:
^(?=[0-9]{4}$|1999-2000|([0-9]{2})[0-8]9-\1[1-9]0|([0-9]{3})[0-8]-\2[1-9])(?:19|20)(?=[^-]*$|([0-9]).*\3.$|09.*10$|19.*20$|29.*30$|39.*40$|49.*50$|59.*60$|69.*70$|79.*80$|89.*90$|99.*00$)[0-9](?=[^-]*$|0.*1$|1.*2$|2.*3$|3.*4$|4.*5$|5.*6$|6.*7$|7.*8$|8.*9$|9.*0$)[0-9](?:-[0-9]{4})?$
解釋:
^ # The start of the string
# This piece prevents 1979-1991 and 1989-2000
(?=
[0-9]{4}$| #either 4 digits
1999-2000| #or 1999-2000
([0-9]{2})[0-8]9-\1[1-9]0| #or first two digits are the same and last digit is 9-0
([0-9]{3})[0-8]-\2[1-9] #or first three digits are the same
)
#now begins the matching
(?:19|20) #Match a 19 or a 20
#This look ahead constricts the to either 4 digits, or to valid transistions for the 3rd digit.
(?=
[^-]*$| #No dash
([0-9]).*\3.$| #Or the same digit
#Or one digit apart.
09.*10$|19.*20$|29.*30$|39.*40$|49.*50$|59.*60$|69.*70$|79.*80$|89.*90$|99.*00$
)
[0-9] #the third digit.
#This look ahead constricts the to either 4 digits, or to valid transistions for the 3rd digit.
(?=
[^-]*$| #No dash
#Or one digit apart.
0.*1$|1.*2$|2.*3$|3.*4$|4.*5$|5.*6$|6.*7$|7.*8$|8.*9$|9.*0$
)
[0-9] #the 4th digit
(?:-[0-9]{4})? #the optional second year.
$ #the end of the string.
這是我想出的正則表達式:
preg_match('/^(((?:19|20)[0-9]{2})(?:-((?:19|20)[0-9]{2}))?)$/', $string)
它將匹配(有效的)單年或雙年。
捕獲組 1 包含完全匹配的內容(無論是 2011 年還是 2011-2012 年),組 2 匹配第一年,組 3 匹配第二年(如果找到)
對於雙年:使用 php 檢查它們是否相隔 1 年
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.