In PHP 7.3+, and depending on the environment, there may be other constants that aren't ints which will cause errors with array_flip. I opted to go with a RegexException and a filter on gk's note.
<?php
class RegexException extends \Exception {
public $errorCode;
public function __construct(
int $errorCode,
string $additionalMessage = null
) {
$this->errorCode = $errorCode;
$errorMessage = $this->getErrorString($errorCode) ?? 'Unknown regex error';
$additionalMessage = $additionalMessage ? " $additionalMessage" : '';
parent::__construct("Regex error thrown: $errorMessage." . $additionalMessage);
}
private function getErrorString(int $errorCode): ?string
{
$pcreConstants = get_defined_constants(true)['pcre'] ?? [];
$pcreConstants = array_filter($pcreConstants, function ($code) {
return is_int($code);
});
$errorStrings = array_flip($pcreConstants);
return $errorStrings[$errorCode] ?? null;
}
Usage:
throw new RegexException(preg_last_error());