0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Yii(PHP)における正規表現

Posted at

Yii(PHP)でよく使われる正規表現(Regex)を紹介します。
特に バリデーションデータチェック に使われるパターンを中心にまとめました。


1. 数字関連

目的 正規表現 説明
数字のみ /^\d+$/ 半角数字のみ許可(整数)
整数(正負含む) /^-?\d+$/ マイナス記号を含む整数
小数(正負含む) /^-?\d+(\.\d+)?$/ 小数点を含む数値
電話番号(ハイフンあり) /^([0-9-])+$/ 090-1234-5678 形式
電話番号(日本国内、10-11桁) /^\d{10,11}$/ 09012345678 形式
郵便番号(日本:123-4567) /^\d{3}-\d{4}$/ 123-4567 のみ許可

2. 文字列関連

目的 正規表現 説明
半角英字のみ /^[a-zA-Z]+$/ 半角英字(大文字・小文字)
半角英数字のみ /^[a-zA-Z0-9]+$/ 半角英数字
半角英数字 + 一部記号 /^[a-zA-Z0-9_-]+$/ ハイフン -、アンダースコア _ を含む
全角ひらがなのみ /^[ぁ-んー]+$/u ひらがなのみ( を含む)
全角カタカナのみ /^[ァ-ヶー]+$/u カタカナのみ( を含む)
全角日本語(漢字・ひらがな・カタカナ) /^[一-龠々ぁ-んァ-ヶー]+$/u 日本語のみ
氏名(ひらがな・カタカナ・漢字) /^[ぁ-んァ-ヶ一-龠々ー\s]+$/u スペースを含む氏名入力

3. メールアドレス

目的 正規表現 説明
メールアドレス(一般的) /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ test@example.com 形式

Yiiでは、メールアドレスのバリデーションは email ルール を使うのが一般的。

[['mail'], 'email']

4. パスワード

目的 正規表現 説明
8文字以上の英数字 /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/ 英字・数字を両方含む8文字以上
8文字以上の英数字+記号 /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,}$/ 記号を含む
大文字・小文字・数字・記号を含む8文字以上 /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/ 強力なパスワード

5. URL

目的 正規表現 説明
URL(http/https) /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ http://example.com

Yiiの url ルールを使うのが一般的:

[['website'], 'url']

6. 日付・時間

目的 正規表現 説明
YYYY/MM/DD /^\d{4}\/\d{2}\/\d{2}$/ 2024/02/21 形式
YYYY-MM-DD /^\d{4}-\d{2}-\d{2}$/ 2024-02-21 形式

Yiiの date ルールを使うのが一般的:

[['birth_date'], 'date', 'format' => 'php:Y-m-d']

7. Yiiでの使い方

Yiiの rules() に正規表現を適用する場合:

public function rules()
{
    return [
        [['mail'], 'match', 'pattern' => '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', 'message' => 'メールアドレスの形式が正しくありません。'],
        [['tel'], 'match', 'pattern' => '/^([0-9-])*$/', 'message' => '電話番号は数字とハイフンのみで入力してください。'],
        [['zip_code'], 'match', 'pattern' => '/^\d{3}-\d{4}$/', 'message' => '郵便番号は「123-4567」の形式で入力してください。'],
        [['password'], 'match', 'pattern' => '/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/', 'message' => 'パスワードは8文字以上で英字と数字を含めてください。'],
    ];
}

8. まとめ

数字系 → /^\d+$/(整数)、/^\d{10,11}$/(電話番号)
文字列系 → /^[ぁ-んー]+$/u(ひらがな)、/^[ァ-ヶー]+$/u(カタカナ)
メール → /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
パスワード → /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/(8文字以上の英数字)
日付・時間 → /^\d{4}-\d{2}-\d{2}$/(YYYY-MM-DD)

参考

Yii 2.0 決定版ガイド:コア・バリデータ

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?