日 | 月 | 火 | 水 | 木 | 金 | 土 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
以前に学習した事がある、PHPでカレンダーを表の中に出力するコードを書いてみました。
phpでカレンダーを表現するのは有名なようで、検索するとコードそのものも出てきますが、
今回のは私が白紙の状態から、以前の学習を思い出しながら、独自に書きました。
書いたものを貼り付けたいと思います。
貼り付けようと思いましたが、コードをそのまま貼り付ければ、当然ブラウザはそれをコードと認識し、
コードの貼り付けになりません。
対処法として、"<"や">"を特殊文字で書くと良いです、が、これを手作業でやるのは困難です。
そこで正規表現を使い、"<"だけ"<"に置換しました。具体的には以下のような方法です。
<?php
$str = "ここに特殊文字に置換したいコードを記入";
print preg_replace('/</', '<', $str);
?>
追記ーー
<?php
$str = "ここに特殊文字に置換したいコードを記入";
print htmlspecialchars($str, ENT_QUOTES);
?>
ーー
<?php
$year_current = date("Y");
$month_name = date("F");
print "<span id='now_year'>$year_current</span>" . " "."$month_name";
?>
<table border="1">
<tr>
<th class="red">日</th>
<th>月</th>
<th>火</th>
<th>水</th>
<th>木</th>
<th>金</th>
<th class="blue">土</th>
</tr><tr>
<?php
$year = date("Y");
$month = date("n");
$day = date("j");
$timestamp = mktime(0,0,0,$month,1,$year);
$week = date("w", $timestamp);
$t = date("t",$timestamp);
$timestamp_last = mktime(0,0,0,$month,$t,$year);
$week_last = date("w", $timestamp_last);
$count = 0;
for($i=0; $i<$week; $i++){
print "<td></td>";
$count++;
}
for($i=1; $i<=$t; $i++){
if($count==7){
print "</tr><tr>";
$count = 0;
}
if($day==$i) print "<td align='right' id='today'>$i</td>";
else if($count==0) print "<td align='right' class='red'>$i</td>";
else if($count==6) print "<td align='right' class='blue'>$i</td>";
else print "<td align='right'>$i</td>";
$count++;
}
for($i=0; $i<6-$week_last; $i++){
print "<td></td>";
$count++;
}
?>
</tr>
</table>