LoginSignup
2
0

More than 5 years have passed since last update.

正規表現を使用して都道府県コードを抽出する。また配列から該当する要素を抽出する。

Posted at

国土交通省だかどこだかかが出している都道府県コードを判定する正規表現が必要だったので書きました。
おまけでPHPを使用した「配列から都道府県コードに該当する要素を抽出する」コードも載せておきます。

正規表現

^([1-9]|0[1-9]|[1-3][0-9]|4[0-7])$

1~47までの数字と0埋めの01~09に当てはまる文字列を検索します。
[1-9]の部分で1~9を、0[1-9]の部分で0埋めの01~09を定義しています。
コピペする場合は必要に応じて該当部分を消すとよいと思います。

配列から都道府県コードに該当する要素を抽出する

※ PHP用に正規表現の文字列にバックスラッシュを追記しています。

a.php
$prefectures = [
    '0',
    '01',
    '2',
    '47',
    '48',
    '100',
    'hogehoge'
];

// 正規表現にマッチする要素のみ抽出する
$match_prefecture = preg_grep('/^([1-9]|0[1-9]|[1-3][0-9]|4[0-7])$/', $prefectures);

// 結果を出力
print_r($prefectures, true);
print_r($match_prefecture, true);

上記コードの出力結果

Array
(
    [0] => 0
    [1] => 01
    [2] => 2
    [3] => 47
    [4] => 48
    [5] => 100
    [6] => hogehoge
)

Array
(
    [1] => 01
    [2] => 2
    [3] => 47
)

めでたしめでたし

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