I am building an admin UI where a user can manage a list PCRE strings which get passed to PHP's preg_match
at other points in my application.
我正在构建一个管理UI,用户可以在其中管理一个列表PCRE字符串,这些字符串在应用程序的其他位置传递给PHP的preg_match。
Before storing the user's input for later use by preg_match
, I'd first like to validate that the user's input is a valid PCRE expression, otherwise later on passing it to preg_match
throws an error.
在存储用户输入供preg_match稍后使用之前,我首先要验证用户的输入是一个有效的PCRE表达式,否则在将其传递给preg_match时将抛出一个错误。
What's the best way to validate a given string to see if it's a valid PCRE in PHP?
验证给定字符串的最佳方法是什么,看它是否是PHP中的有效PCRE ?
1 个解决方案
#1
3
Your best bet will be to just pass the string to preg_match, and catch any errors that happen.
最好的方法是将字符串传递给preg_match,并捕获发生的任何错误。
try{
preg_match($in_regex, $string, $results);
//Use $results
} catch (Exception $e) {
echo "Sorry, bad regex (/" . $in_regex . "/)";
}
[Edit] Since that won't work, you could try:
[编辑]既然行不通,你可以试试:
function bad_regex($errno, $errstr, $errfile, $errline){
echo "Sorry, bad regex.";
}
set_error_handler("bad_regex");
preg_match($in_regex, $string, $results);
restore_error_handler();
#1
3
Your best bet will be to just pass the string to preg_match, and catch any errors that happen.
最好的方法是将字符串传递给preg_match,并捕获发生的任何错误。
try{
preg_match($in_regex, $string, $results);
//Use $results
} catch (Exception $e) {
echo "Sorry, bad regex (/" . $in_regex . "/)";
}
[Edit] Since that won't work, you could try:
[编辑]既然行不通,你可以试试:
function bad_regex($errno, $errstr, $errfile, $errline){
echo "Sorry, bad regex.";
}
set_error_handler("bad_regex");
preg_match($in_regex, $string, $results);
restore_error_handler();