Format a string so that it will match against a given PCRE
require 'ReversedRegex.php';
$parser = new RegexParser('^/blog/(?<post_id>\d+)/.+$');
$reversed = new ReversedRegex($parser->regex()); // parse regex & reverse it
echo $reversed->format([
'post_id' => 15, // can be formatted by name or with index 0
1 => 'My post title' // '.+' requires formatting too
]);
> /blog/15/My post title
- Character classes:
.
,\w
,\W
,\d
,\D
,\s
,\S
,[abcdefg]
- Variable-length repetitions of literals and non-literals: base+, base*, base?, base{2,3}, base{2,}. Note that if base is not a literal, you should provide a single formatting parameter to satisfy both base and the repetition.
- Fixed-length repetitions of non-literals: base{4}. Same as above
- Reversed lookarounds: (?!abc), (?<!abc)
There's no verification at all. Consider the regex in the 'Example usage' section and the following code:
echo $reversed->format(['post_id' => 'lol', 1 => '']);
> /blog/lol/
This will not match against the regex. You should use something like preg_match on the output if you need verification.
Groups, named groups, character classes, lookarounds, anchors, string literals and repetitions
- Alternations (i.e. pipe operator): It is not possible to determine which side of the operation to format without further inspection of the involved argument counts, types and matching tokens.
$p = new RegexParser('\d+|[a-zA-Z]+');
$r = new ReversedRegex($p->regex());
$r->format(['hello']); // which one?
- Backreferences: There is not a 1:1 relation between groups and formatting placeholders in some cases. More specifically, PCRE dictates that when a group is repeated the backreference matches the last captured value of the group. However, we format both the group and the repetition with a single value. The problem gets increasingly difficult when the group contains variable-length repetitions.
$p = new RegexParser('(\d)+\1');
$r = new ReversedRegex($p->regex());
$r->format(['123']); // (\d)+ formatted as '123', but how to tell what is '\1'?