note 124754 added to function.preg-last-error
| From: | zerodahero at gmail dot com | Date: | Tue, 25 Feb 2020 00:51:28 +0000 |
| Subject: | note 124754 added to function.preg-last-error | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214218@lists.php.net to get a copy of this message | ||
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);
}
/**
* Gets an error string (const name) for the PCRE error code
*
* @param int $errorCode
*
* @return string|null
*/
private function getErrorString(int $errorCode): ?string
{
$pcreConstants = get_defined_constants(true)['pcre'] ?? [];
/*
* NOTE: preg_last_error() returns an int, but there are constants
* in PHP 7.3+ that are strings, bools, or otherwise. We can pretty
* safely filter out the non-integers to fetch the appropriate
* error constant name.
*/
$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());
----
Server IP: 45.112.84.4
Probable Submitter: 38.142.137.34 (proxied: 66.41.143.160)
----
Manual Page -- http://php.net/manual/en/function.preg-last-error.php
Edit -- https://master.php.net/note/edit/124754
Del: integrated -- https://master.php.net/note/delete/124754/integrated
Del: useless -- https://master.php.net/note/delete/124754/useless
Del: bad code -- https://master.php.net/note/delete/124754/bad+code
Del: spam -- https://master.php.net/note/delete/124754/spam
Del: non-english -- https://master.php.net/note/delete/124754/non-english
Del: in docs -- https://master.php.net/note/delete/124754/in+docs
Del: other reasons-- https://master.php.net/note/delete/124754
Reject -- https://master.php.net/note/reject/124754
Search -- https://master.php.net/manage/user-notes.php