printfのフォーマットから、変換指定子を抜き出す正規表現

そんなに用途は無いと思うんですが、PHPのpirntf構文やsprintf構文のフォーマットから変換指定子(%sや%d等)を抜き出す正規表現を書いてみました。

1
/(?:^|[^%])%(?:[0-9]+\$)?(?:[\+\-]?(?:0|\'[^%])?[\d]*?(?:\.\d+)?)?[bcdeEufFgGosxX]/u

preg_match_allなどで利用すれば、変換指定子が何個使用されているかなどを調べることができると思います。

用途

プログラム中でprintf構文に必要とされる引数の数を調べなくてはならなくなり、下記のような関数を作って利用しています。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function _argAmount($pattern)
{
    preg_match_all(
        '/(?:^|[^%])%(?:([0-9]+)\$)?(?:[\+\-]?(?:0|\'[^%])?[\d]*?(?:\.\d+)?)?[bcdeEufFgGosxX]/',
        $pattern,
        $matches
    );
 
    $count = 0;
 
    if (!empty($matches[1])) {
        $filtered = array_filter($matches[1]);
        $max = max($filtered);
        $empty = count($matches[1]) - count($filtered);
        $count = ($max > $empty) ? $max : $empty;
    }
 
    return $count;
}