superm
superm

Reputation: 21

php regex finding double brackets

I have some text that is submitted, and it will contain words in double brackets, but there can be some only in single brackets. But I only want the ones in double brackets.

Example:

[[test]] [test1] [[test2]] [test5] [[test3]]

With other words etc in the same string...

So for instance:

[[test]] the quick [test1] brown [[test2]] fox [[test3]] jumped [mytest] over the lazy [[test4]] dog

Right now I have a preg_match_all with:

(preg_match_all('/\\[.*?\\]\\]/is',$str,$match))

But, it also pulls the single bracket ones... and I suck at regex.

Does anyone have any input on how I can pull just the double bracket ones?

Thanks!

Upvotes: 2

Views: 1262

Answers (1)

chris85
chris85

Reputation: 23892

Use this instead.

\[{2}.*?\]{2}

Demo: https://regex101.com/r/bW0mM6/1

The {2} requires 2 occurrences. You are only checking for one bracket with your expression.

PHP Demo: http://sandbox.onlinephpfunctions.com/code/2f16f7e102d822e31dc128a384f8090181c7461d

PHP Usage:

$str = '[[test]] [test1] [[test2]] [test5] [[test3]]';
preg_match_all('/\[{2}(.*?)\]{2}/is',$str,$match);
print_r($match[1]);

Output:

Array
(
    [0] => test
    [1] => test2
    [2] => test3
)

Also note I captured the double bracketed values in the PHP demo, not sure if that is what you wanted.

Upvotes: 6

Related Questions