php / php/doc-en

PCRE: Unmatched capture groups result inconsistency

Open
#2,522 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Extension: pcre
Dominant language
XML
Stars
596
Forks
890
Avg merge
1d 15h
Merged PRs (30d)
55

Description

Description

Currently, unmatched capture groups are added to the result when they are before matched capture group, but are not added when they are after (ie. unmatched capture group is not followed by any other matched capture group).


The docs about "PREG_UNMATCHED_AS_NULL" flag says:

If this flag is passed, unmatched subpatterns are reported as null; otherwise they are reported as an empty string.

So all capture groups, even the unmatched at the end, should be always present.


The following code:

<?php

preg_match('/(?<foo>y)?x(?<bar>y)?/', 'x', $matches);
print_r($matches);

preg_match('/(?<foo>y)?()x(?<bar>y)?/', 'x', $matches); // notice extra "()"
print_r($matches);

Resulted in this output:

Array
(
    [0] => x
)
Array
(
    [0] => x
    [foo] => 
    [1] => 
    [2] => 
)

But I expected this output instead:

Array
(
    [0] => x
    [foo] => 
    [1] => 
    [2] => 
    [bar] => 
    [3] => 
)
Array
(
    [0] => x
    [foo] => 
    [1] => 
    [2] => 
    [bar] => 
    [3] => 
)

online repro: https://3v4l.org/ra13Q

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the documentation for PREG_UNMATCHED_AS_NULL and reproduce both preg_match examples from the issue. Compare the documented behavior with the observed capture-group arrays and determine whether the documentation or PHP behavior is the intended correction. Done means the issue's expected handling of trailing unmatched groups is resolved consistently.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
documentation
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.