How to get first preg match elements

34 Views Asked by At

I need with preg_match_all() to extract all [ANY_TEXT-pb] blocks.

My code:

$content = 'START Text1 [news-block] text2 [title1-pb] text3 text4 [title2-pb] text5 END';
preg_match_all('/\[(.*?)pb\]/si', $content, $codes);
print_r($codes[0]);

What I need to get:

Array
(
    [0] => [title1-pb]
    [1] => [title2-pb]
)

What I get now:

Array
(
    [0] => [news-block] text2 [title1-pb]
    [1] => [title2-pb]
)

How to detect the first "[" element from the same block? Looks like now this preg takes first "[" from all string.

1

There are 1 best solutions below

0
The fourth bird On

Looking at the desired result, you should not cross matching square brackets using a negated character class.

For a match only, you don't need the capture group, so you can omit the parenthesis:

\[[^][]*pb\]

See a regex demo: