1

i'm trying to parse tags from a string like the following:

$string = "foo [cmd:tag1] bar [cmd:tag2] bla bla";
$pattern = "/\[cmd:(.+)\]/";
preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
$rc = $matches[0];
foreach($rc as $tag)
{
    print_r2($tag);
}

which will return:

Array
(
    [0] => [cmd:tag1] bar [cmd:tag2]
    [1] => 4
)

what is wrong in my syntax as i'm expecting the following result:

Array
(
    [0] => [cmd:tag1]
    [1] => [cmd:tag2]
)

thanks

Fuxi
  • 7,611
  • 25
  • 93
  • 139

1 Answers1

3
\[cmd:(.+?)\]

or use

\[cmd:([^\]]*)\]

Make your quantifier * non greedy by putting ? ahead of it.

See demo.

https://regex101.com/r/fA6wE2/23

vks
  • 67,027
  • 10
  • 91
  • 124