Nate Higgins
Nate Higgins

Reputation: 2114

Validate regex without throwing warning

I'm trying to validate that a string contains a regular expression, and that it is a valid one in PHP. Usually, I'd do this in the following way

<?php
@preg_match($string, '') !== false;

That generates a warning, which is fine because we use @ to suppress it. However, problems arise when we use set_error_handler to catch errors, as the handler will still be triggered, despite the @ supressor.

I'd like to do something similar to the code provided, without it throwing a warning.

The warning thrown is:

preg_match(): Delimiter must not be alphanumeric or backslash

Upvotes: 0

Views: 262

Answers (1)

linepogl
linepogl

Reputation: 9355

Just add this in your error handler:

function user_error_handler($severity, $msg, $filename, $linenum, $content) {
    if (0 == (error_reporting() & $severity)) return;
    ...
}

In this case, because of the @ operator, error_reporting() will return 0.

Upvotes: 3

Related Questions