Daniel Williams
Daniel Williams

Reputation: 2317

Get all occurances of string pattern in variable using preg_match_all

I have a variable, for example:

$str = 'a string1 ab string2 abc string3 abcd string4 abcde string1 abcdef string2';

I want to use preg_match_all to get all unique occurrences of string(n).

My code so far is:

preg_match_all('%string([0-9])%', $str, $matches);

What I want is to return the $matches array that looks like:

Array (
[0] => 'string1'
[1] => 'string2'
[2] => 'string3'
[3] => 'string4'
)

But instead I get multiple nested arrays

Upvotes: 0

Views: 23

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521028

Your current syntax is fine, but the reason you are getting a nested array is because you have defined a capture group around the number in string1, string2, etc. Remove that unwanted capture group, remove duplicates, and you will get the behavior you want here.

$str = 'a string1 ab string2 abc string3 abcd string4 abcde string1 abcdef string2';
preg_match_all('/\bstring[0-9]+\b/', $str, $matches);
$strings = array_unique($matches[0]);
print_r($strings);

This prints:

Array
(
    [0] => string1
    [1] => string2
    [2] => string3
    [3] => string4
)

Upvotes: 1

Related Questions