0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP preg_match()関数: 正規表現によるマッチングを行う

0
Posted at

😄この投稿は、codingeverybody.jpのコンテンツをもとに作成しています。

(PHPバージョン4+)

定義と使い方

preg_match()関数は、指定された正規表現パターンを使用して、文字列内に一致(match)する部分を検索します。

特徴

  • 一致するパターンが文字列内で最初に検出された時点で検索を中断し、1を返します。
  • 一致するパターンが見つからない場合は0を返します。
  • エラーが発生した場合はfalseを返します。
  • メールアドレス、電話番号、URLなどの特定パターンの文字列を検証する際によく使用されます。
  • 文字列内から特定のパターンを検索したり、文字列から特定の形式のデータを抽出したりする用途にも使用されます。

基本例

$email = "codingeverybody@example.com";
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";

if (preg_match($pattern, $email)) {
    echo 'メールアドレスは正しい形式です。';
} else {
    echo 'メールアドレスは正しい形式ではありません。';
}

// 出力: 'メールアドレスは正しい形式です。'

構文

preg_match(
    string $pattern,
    string $subject,
    array &$matches = null,
    int $flags = 0,
    int $offset = 0
): int|false

/* preg_match(
    正規表現パターン,
    検索対象となる文字列,
    一致した部分を格納する配列[,
    追加設定を指定するフラグ[,
    検索を開始する文字列内のオフセット]]
);
*/

戻り値

一致するパターンが文字列内で最初に検出された時点で検索を中断し、1を返します。一致するパターンが見つからない場合は0を返します。エラーが発生した場合はfalseを返します。

例

# 数字の抽出

$text = '価格は500ウォンです。';
$pattern = "/\d+/";

if (preg_match($pattern, $text, $matches)) {
    echo '見つかった数字: ' . $matches[0];
} else {
    echo '数字が見つかりません。';
}

// 出力: '見つかった数字: 500'

# URLからドメインを抽出

$url = 'https://www.example.com/page';
$pattern = "/https:\/\/(www\.)?([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,6})\/([a-zA-Z0-9.-\/]*)/";

if (preg_match($pattern, $url, $matches)) {
    $domain = $matches[2];
    echo '抽出されたドメイン: ' . $domain;
} else {
    echo 'ドメインが見つかりません。';
}

// 出力: '抽出されたドメイン: example'

参考資料

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?