LoginSignup
2
0

More than 1 year has passed since last update.

PHPのpreg_match()でよく使う正規表現の備忘録

Last updated at Posted at 2022-04-25

PHPのpreg_match()をよく使うのですが、毎度毎度正規表現を調べており面倒であったため、よく使うものを備忘録として残します。

本記事の環境

ホストOS:Windows10 Pro 64bit 16GB
ゲストOS:Red Hat Enterprise Linux 8.3 (Ootpa)
Oracle VM VirtualBox:6.0.4a
vagrant:Vagrant 2.2.14
Apache:2.4.37
Tera Term:4.105
PHP:7.4

// 空である場合
if (preg_match("/\A[  \t\r\n]+\z/", XXX) || (XXX == "")) {
}

// 月(01~12)である場合
if (preg_match("/\A(0[1-9]|1[0-2])\z/", XXX)) {
}

// 英数字である場合
if (preg_match("/\A[a-zA-Z0-9]+\z/", XXX)) {
}

// テキストファイル(.txt)である場合
if (preg_match("/\.txt/i", XXX)) {
}

// 日本語、英数字、スペースを許可する場合
if (preg_match("/\A[ぁ-んァ-ヶーa-zA-Z0-9一-龠0-9  ]+\z/", XXX)) {
}

// 半角英数字混在で6桁以上20桁以下(=パスワードチェックで使う想定)
if (preg_match("/\A(?=.*?[A-z])(?=.*?\d)[A-z\d]{6,20}+\z/", XXX)) {
}

// 半角数字で6桁以上20桁以下(=パスワードチェックで使う想定)
if (preg_match("/\A\d{6,20}\z/", XXX)) {
}

// 半角英数字で6桁以上20桁以下(=パスワードチェックで使う想定)
if (preg_match("/\A\w{6,20}\z/", XXX)) {
}
2
0
2

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