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?

More than 1 year has passed since last update.

PHPの正規表現で文字列の一部のみ切り出す

Last updated at Posted at 2023-06-29

正規表現で一致したデータの一部を取得する

PHP: preg_match

マッチする文字列の取得

  • マッチした文字列が第三引数に入る
preg_match('/Harry Potter/', 'Mr. Harry Potter', $matches);
var_dump($matches);

// array(1) {
//   [0]=>
//   string(12) "Harry Potter"
// }

マッチする文字列の一部を取得

  • 括弧で囲んだ部分にマッチした文字列が取得できる
preg_match('/(Harry) (Potter)/', 'Mr. Harry Potter', $matches);
var_dump($matches);

// array(3) {
//   [0]=>
//   string(12) "Harry Potter"
//   [1]=>
//   string(5) "Harry"
//   [2]=>
//   string(6) "Potter"
// }

var_dump($matches[1]);

// string(5) "Harry"

例えばこういう時に便利

User-Agentから桁数が不定なバージョン情報を取得

$user_agent = 'AppVer/105/hogehoge';
preg_match('/(^AppVer\/)(\d+)(\/hogehoge)/', $user_agent, $matches);

if (version_compare($matches[2], '105', '>=')) {
    var_dump("アプリバージョンは {$matches[2]} 以上です。");
} else {
    var_dump("アプリバージョンは {$matches[2]} 未満です。");
}

// string(47) "アプリバージョンは 105 以上です。"
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?