1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
/* ----------------------------------------------------------------------------
 *       正規表現のpreg_matchの【再帰的パターン】専用のシーケンス (?R) の例
 *
 *  作成: 2015.07.28 yoshi of CXMedia Inc.
 * --------------------------------------------------------------------------- */
header("Content-type:text/plain; charset=UTF-8");

// このパターンは開き括弧と最後に閉じ括弧にマッチします。
// 括弧以外の並びまたはパターン自体に再帰的にマッチする部分文字列に何回でもマッチします。
// マッチ文字列に対するバックトラックを禁止の正規表現パターン「(?&gt;xx|yy)」を利用

$str '(ab(cd)ef)';
preg_match("/\((((?>[^()]+)|(?R))*)\)/",$str,$matches);
echo 
"■再帰的パターンの取得「()の場合」\n";
print_r($matches);

// 「(?:xx|yy)」を利用
// <>のネストして、値:efを得る
$str '<ab<cd>ef>';
preg_match("/<((?:(?(R)\w+|([^<>]+))|(?R))*)>/",$str,$matches);
echo 
"\n■再帰的パターンの取得「<>の場合」\n";
print_r($matches);
?>