Re: Pre-RFC: adding a Regex\CompiledRegex class for compiling regular expressions
| From: | Osama Aldemeery | Date: | Sat, 26 Sep 2026 04:03:01 +0000 |
| Subject: | Re: Pre-RFC: adding a Regex\CompiledRegex class for compiling regular expressions | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-132647@lists.php.net to get a copy of this message | ||
Hi Gina,
> Hello internals,
>
> I spent the day prototyping an alternative to the PREG_THROW_ON_ERROR RFC as I'm not fully
> a fan of the approach.
> It can be found as the following PR:
> https://github.com/php/php-src/pull/23868
>
> The basic idea is to add a new Regex\CompiledRegex class that takes a pattern, and some boolean
> modifiers, to compile a regular expression before passing it to the preg_* functions.
I really like the idea, but I am not quite sure it fully replaces the
PREG_THROW_ON_ERROR flag.
Compilation errors are only half of the error story...the other half
happens at match time, on patterns that compiled just fine.
Consider this:
```
$r = preg_match('/(a+)+$/', str_repeat('a', 20) . '!');
var_dump($r); // bool(false)
var_dump(preg_last_error_msg()); // string(25) "Backtrack limit exhausted"
```
As far as I understand, this class of errors
(PREG_BACKTRACK_LIMIT_ERROR, PREG_RECURSION_LIMIT_ERROR,
PREG_JIT_STACKLIMIT_ERROR, ...etc) depends on the subject, not the
pattern, so no amount of validation at construction time can catch it.
I think the proposal, though, removes a good part of the motivation
for PREG_THROW_ON_ERROR, so now whether PHP should have a regex
object that fails on compilation errors only and works with preg_*
functions, or have a flag that guarantees the next line after a
preg_* call only executes if the call left no error behind (or
both?), is up to you and the people on this list to decide. I
personally see the two as complementary rather than alternatives.
That said, I really like and am in support of having a class that
represents a compiled regex (for what my entirely non-voting opinion
is worth), whether it replaces the flag or not.
Best,
Osama