通常使用checkdate()檢測時間是否正確,
今天想試試看,利用preg_match()作多一層的格式確認,
首先,先做一個簡易表單方便送值進去,
其實也可以直接寫在程式碼裡面測試,這樣就不用再寫form,
純粹看個人習慣,
這邊用GET的網址傳値,
順便在url檢視送進去的值,
(當然如果是password等就再用POST,這邊只是純練習)
<html>
<head></head>
<body>
<form method="get">
Date:<input type="text" name="date" />
<input type="submit" name="send" />
</form>
</body>
</html>
作出來的表單:
<?php
$date = $_GET[date];
//Check if date is in YYYY-MM-DD format
function checkDateFormat($date)
{
//match the format of date by preg_match()
//"^" 以指定字元或字串起始
//"$" 以指定字元或字串結束
//"\d" 與[0-9]相同,比對任何數字字元
//"{n}" 指定字元出現n次
if (preg_match ("/^([0-9]{4})([0-9]{2})([0-9]{2})$/", $date, $parts))
{
//check weather the date is valid of not
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
}
else
return false;
}
if(checkDateFormat($date))
{
echo 'yes it is right!!';
} else
echo 'something might be wrong!!';
?>
寫好我的checkDateFormat()後,接下來就是測試噜,TEST 1.
input=123
TEST 2.
input=1987/09/27
TEST 3.
input=19870927

沒有留言:
張貼留言