> On Oct 1, 2025, at 4:01 AM, Alexandre Daubois <[email protected]> 
> wrote:
> 
> Hi everyone,
> 
> I stumbled across the following issue, proposing to add a way to validate 
> regex. [1]
> 
> There is currently no way of knowing if a regex pattern is valid, apart from 
> writing clunky code. [2]

Could you expand on how you define clunky here? I am curious, because I 
validate PCRE patterns like this using the existing mechanisms.

    function is_valid_preg_pattern( $pattern ) {
        $is_valid = true;

        set_error_handler( function () use ( &$is_valid ) { $is_valid = false; 
return true; }, E_WARNING );
        preg_match( $pattern, '' );
        restore_error_handler();

        return $is_valid;
    }

And this is based on the note in the man page for `preg_match()`…

    If the regex pattern passed does not compile to a valid regex, an E_WARNING 
<dfile:///Users/dmsnell/Library/Application%20Support/Dash/DocSets/PHP/PHP.docset/Contents/Resources/Documents/www.php.net/manual/en/errorfunc.constants.html#constant.e-warning>
 is emitted.

Given the possible error conditions, I thought this was comprehensive and the 
only way for the `E_WARNING` to trigger when provided with the empty string is 
if the pattern fails to compile. Given the concerns that Juliette raised with 
regards to multiple regex engines, this one seems like it should be universal 
too.

If there’s something clunky about this, it would aid my curiosity to learn. The 
`$errstr` parameter can also be inspected to ensure that it starts with 
`preg_match()` if there’s a chance any other warning could conflate with an 
unrecognized pattern.

Caveat: I’m not aware of any performance implications for calling 
`set_error_handler()` like this.

> 
> Two propositions emerged from the issue: either create a dedicated 
> "preg_validate()" function, or add a new flag to "filter_var()", namely 
> FILTER_VALIDATE_REGEX_PATTERN.
> 
> I would be in favor of the latter. The approach and implementation would 
> surely be simpler. I don't feel like we should do advanced error management. 
> Knowing if a pattern is valid or not would suffice for the vast majority of 
> cases.
> 
> I don't think the second approach would require an RFC. Christoph thinks that 
> this should at least be announced on the mailing list, so here we are.
> 
> Looking forward to your feedback.
> 
> — Alexandre Daubois
> 
> [1] https://github.com/php/php-src/issues/9289
> [2] https://stackoverflow.com/questions/4440626/how-can-i-validate-regex

Warmly,
Dennis Snell

Reply via email to