42

角かっこで囲まれたテキストをキャプチャする方法が必要です。したがって、たとえば、次の文字列:

[This] is a [test] string, [eat] my [shorts].

次の配列を作成するために使用できます。

Array ( 
     [0] => [This] 
     [1] => [test] 
     [2] => [eat] 
     [3] => [shorts] 
)

次の正規表現があり/\[.*?\]/ますが、最初のインスタンスのみをキャプチャするため、次のようになります。

Array ( [0] => [This] )

必要な出力を取得するにはどうすればよいですか?角かっこはネストされないため、問題にはなりません。

4

1 に答える 1

113

すべての文字列を角かっこで囲みます。

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);

角かっこなしの文字列が必要な場合:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);

角かっこなしのマッチングの代替の低速バージョン(「[^]」の代わりに「*」を使用):

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[(.*?)\]/", $text, $matches);
var_dump($matches[1]);
于 2012-04-11T10:53:03.290 に答える