MrUpsidown
MrUpsidown

Reputation: 22493

PHP Regex returns array of 2 identical strings

Consider the following string and Regex:

$string = 'xxx-zzzzzz-xxx';
preg_match('/(?<=xxx-)(.*)(?=-xxx)/', $string, $extract);

var_dump($extract);

This outputs:

array (size=2)
  0 => string 'zzzzzz' (length=6)
  1 => string 'zzzzzz' (length=6)

Why do I get an array size of 2 since the matched string only appears once? And how would I do to get only a string or an array with 1 string? Thanks in advance.

Upvotes: 1

Views: 209

Answers (2)

Duroth
Duroth

Reputation: 6581

From the PHP Manual:

If $matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

In other words, matches[0] returns the full match, with other keys in the array returning only partial matches (equal to the number of () used in your regular expression).

Keep in mind that preg_match will only ever match one complete result; if you want to return all matches in a given string, have a look at preg_match_all() instead.

Upvotes: 3

anubhava
anubhava

Reputation: 785711

index=0 is whole match and index=1 (and onwards) is first captured group. If you don't want captured group then just use:

/(?<=xxx-).*(?=-xxx)/

i.e.

preg_match('/(?<=xxx-).*(?=-xxx)/', $string, $extract);
print_r($extract);

Upvotes: 3

Related Questions