note 80221 deleted from ref.pcre by derick
| From: | derick@php.net | Date: | Mon, 14 Jul 2008 08:19:38 +0000 |
| Subject: | note 80221 deleted from ref.pcre by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-141467@lists.php.net to get a copy of this message | ||
Note Submitter: me at codingbear.com
----
While developing an application I needed to take user-entered regular expressions and validate them
before use. Since I was unable to find a built-in function for doing so, I wrote this piece of code.
It works by setting an error handler then using the provided regular expression on an empty string.
If the regular expression is invalid then preg_match will create an error which is captured by the
error handler. The error handler is then restored.
It is possible to generalize this for any function by modifying isValid() to accept a
function/method name and the appropriate parameters instead.
For aesthetics, the preg_match(): part of the error is stripped out.
<?php
/**
* The RegEx validation class .
*
* Usage:
* if (!RegEx::isValid($expression)) {
* echo 'Your regular expression is invalid because: ' . RegEx::error();
* }
*/
class RegEx {
/**
* Validates a regular expression. Returns TRUE
* if the expression is valid, FALSE if not. If
* the expression is not valid, the reason why
* can be fetched from RegEx::error().
*
* @access public
* @static
* @param string $regex Regular Expression
* @return bool
*/
function isValid($regex)
{
RegEx::error(FALSE);
set_error_handler(array('RegEx', 'errorHandler'));
preg_match($regex, '');
restore_error_handler();
return (RegEx::error() === FALSE) ? TRUE : FALSE;
}
/**
* Error handler for RegEx. Used internally by RegEx::validate()
*
* @access package
* @static
* @param int $code Error Code
* @param string $message Error Message
*/
function errorHandler($code, $message)
{
// Cuts off the 'preg_match(): ' part of the error message.
$error = substr($message, 14);
// Sets the error flag with the message.
RegEx::error($error);
}
/**
* Holds the error from the last validation check.
*
* The first parameter is used internally and should
* not be used by the developer.
*
* @access public
* @static
* @param FALSE|string $value value to set for $flag
* @return FALSE|string
*/
function error($value = NULL)
{
static $flag = FALSE;
if (!is_null($value))
{
$flag = $value;
}
return $flag;
}
}
?>