1

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.

0

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.