1 minute read

学んだこと

正規表現で郵便番号を検査する

  • preg_match を使って正規表現で郵便番号かどうか確認をする。
    • /\A\d{3}[-]\d{4}\z/の意味は以下の通り。
    • 整数3桁 - 整数4桁の形になっているか確認する正規表現となる。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php
    $zip = '123-4567';
    if(preg_match("/\A\d{3}[-]\d{4}\z/", $zip)){
        echo '郵便番号: 〒' . $zip;
    }else{
        echo '郵便番号を正しくご記入ください';
    }
    ?>
</body>
</html>

別のページにジャンプさせる

  • header を使って別のページにジャンプさせる。
    • header は HTTP ヘッダを送信する関数。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php
    header('Location: https://tomosta.jp');
    exit();
    ?>
</body>
</html>

剰余算を使って 1 行ごとに表の色を変える

  • C++や C#の書き方とほとんど変わらず。
  • 変数 % 割る数で余りの数が出力される。
  • その特性を利用し、下記では、2 で割った余りが 1 の場合表の色を変化させている。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table>
        <?php for($i = 1; $i <= 10; $i++):?>
            <?php if($i % 2 === 1):?>
                <tr style="background-color: #ccc">
            <?php else: ?>
                <tr>
            <?php endif; ?>
            <td><?php echo $i;?>行目</td>
            <td>ABC</td>
            </tr>
        <?php endfor;?>
    </table>
</body>
</html>

  • ページ内で宣言していた変数は、ページをまたぐとその変数は扱うことができない。
  • そのため、Cookie を使うことでページをまたいた際でも使用することが可能。

index.php

  • setcookie('Cookieに保存する変数', '変数の中身', 有効期間)で Cookie に保存することができる。
    • 下記では有効期間として、明日の同じ時刻+14 秒まで保存する設定となっている。
<a href="page02.php">2ページ目</a>
    <?php
    $value = '変数に保存した値です';
    setcookie('message', 'Cookieに保存した値です', time() + 60 * 60 * 24 * 14);
    ?>
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
  </body>
</html>

page02.php

  • $_COOKIE['Cookieに保存している変数']で Cookie に保存している変数を取得することができる。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page02</title>
</head>
<body>
    変数の値: <?php echo $value; ?><br>
    Cookie: <?php echo $_COOKIE['message'];?>
</body>
</html>

  • デベロッパーツールで Cookie が保存されているか index.php で確認 alt text

  • 同じく page02.php でも確認 alt text

Tags:

Updated: