Skip to content

Commit

Permalink
Fix #2907: Allow Escaped % in String Format Match
Browse files Browse the repository at this point in the history
For example, the format '%%d' should match the string literal '%d'.

We achieve this by using negative lookbehind
(http://php.net/manual/en/regexp.reference.assertions.php) when
constructing the regex pattern that we will match against.
  • Loading branch information
mkasberg authored and sebastianbergmann committed Dec 11, 2017
1 parent 1e78561 commit 694dec1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/Framework/Constraint/StringMatchesFormatDescription.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,19 @@ protected function additionalFailureDescription($other)

protected function createPatternFromFormat($string)
{
$string = \str_replace(
$string = \preg_replace(
[
'%e',
'%s',
'%S',
'%a',
'%A',
'%w',
'%i',
'%d',
'%x',
'%f',
'%c'
'/(?<!%)%e/',
'/(?<!%)%s/',
'/(?<!%)%S/',
'/(?<!%)%a/',
'/(?<!%)%A/',
'/(?<!%)%w/',
'/(?<!%)%i/',
'/(?<!%)%d/',
'/(?<!%)%x/',
'/(?<!%)%f/',
'/(?<!%)%c/'
],
[
'\\' . DIRECTORY_SEPARATOR,
Expand All @@ -96,6 +96,8 @@ protected function createPatternFromFormat($string)
\preg_quote($string, '/')
);

$string = \str_replace('%%', '%', $string);

return '/^' . $string . '$/s';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ public function evaluateDataProvider()
false,
'%c',
'abc'
],
'Escaped %' => [
true,
'Escaped %%e %%s %%S %%a %%A %%w %%i %%d %%x %%f %%c',
'Escaped %e %s %S %a %A %w %i %d %x %f %c'
]
];
}
Expand Down

0 comments on commit 694dec1

Please sign in to comment.