Bartosz Stokrocki
Bartosz Stokrocki

Reputation: 23

PHP preg_match matches

I'm trying to get all the matches from string:

$string = '[RAND_15]d4trg[RAND_23]';

with preg_match like this:

$match = array();
preg_match('#\[RAND_.*]#', $string, $match);

but after that $match array looks like this:

Array ( [0] => [RAND_15]d4trg[RAND_23] )

What should I do to get both occurrences as 2 separate elements in $match array? I would like to get result like this:

$match[0] = [RAND_15];
$match[1] = [RAND_23];

Upvotes: 2

Views: 3649

Answers (1)

raina77ow
raina77ow

Reputation: 106385

Use ...

$match = array();
preg_match_all('#\[RAND_.*?]#', $string, $match);

... instead. ? modifier will make the pattern become 'lazy', matching the shortest possible substring. Without it the pattern will try to cover the maximum distance possible, and technically, [RAND_15]d4trg[RAND_23] does match the pattern.

Another way is restricting the set of characters to match with negated character class:

$match = array();
preg_match_all('#\[RAND_[^]]*]#', $string, $match);

This way we won't have to turn the quantifier into a lazy one, as [^]] character class will stop matching at the first ] symbol.

Still, to catch all the matches you should use preg_match_all instead of preg_match. Here's the demo illustrating the difference.

Upvotes: 5

Related Questions