Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Type/Regex/RegexGroupParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ public function parseGroups(string $regex): ?RegexAstWalkResult

if (str_contains($modifiers, 'x')) {
// in freespacing mode the # character starts a comment and runs until the end of the line
$regex = preg_replace('/(?<!\?)#.*/', '', $regex) ?? '';
// but \# is an escaped literal hash, and (?#...) is an inline comment - neither starts a line comment
$regex = preg_replace('/(?<!\\\\)(?<!\(\?)#.*/', '', $regex) ?? '';
}

$rawRegex = $this->regexExpressionHelper->removeDelimitersAndModifiers($regex);
Expand Down
15 changes: 15 additions & 0 deletions tests/PHPStan/Analyser/nsrt/preg_match_shapes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1073,3 +1073,18 @@ function bug12792(string $string): void {
assertType('array{string, non-empty-string}', $match); // could be array{'acd'|'ayd'|'bd', 'c'|'xb'|'y'}
}
}

function testExtendedSyntaxEscapedHash(string $string): void {
// \# in extended mode should be treated as literal hash, not comment
if (preg_match('/^ ([\#.]) $/x', $string, $matches)) {
assertType("array{non-falsy-string, '#'|'.'}", $matches);
}

// Real comment vs escaped hash
if (preg_match('/
(\d+) # this is a comment
([\#ab]+) # hash in character class (escaped)
/x', $string, $matches)) {
assertType('array{non-falsy-string, numeric-string, non-empty-string}', $matches);
}
}
Loading