0
0

More than 1 year has passed since last update.

【正規表現】PHPで郵便番号をIF文で条件定義

Posted at
test.php
<?php
$code = '0011-0012';

if(preg_match("/\A\d{3}[-]\d{4}\z/",$code)){
    echo('郵便番号:〒'.$code);
}else {
    echo('※郵便番号は000-0000の形式でご記入ください');
}

?>

説明


①preg_match — 正規表現によるマッチングを行う
https://www.php.net/manual/ja/function.preg-match.php

②/\A ←ここまでの意味・・・文字列の先頭を意味します。

③\d{3} ←これの意味・・・「d」が数字指定、{3}数。数字で3文字入力しなさい。

④[-] ←これの意味・・・郵便番号のハイフンです。ハイフン無し入力をユーザーにした正規表現を記述したい場合はこれは不要です。

⑤\d{4} ←これの意味・・・「d」が数字指定、{4}数。数字で4文字入力しなさい。

⑥\z/ ←これの意味・・・文字列の末尾を意味します。

test.php
preg_match("/\A\d{3}[-]\d{4}\z/");
//000-0000の形式で入力するよう正規表現を定義。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0