PHP에서 정규식 컴파일 오류를 쉽게 확인할 수 있습니다. 자체 오류 처리기를 등록하십시오. 정규 표현식 컴파일 오류를 탐지하고 파일 이름 및 행 번호와 같은 중요한 정보를 표시하지 않고 사용자에게보고하는 PHP 정규식 테스터를 작성했습니다. 여기서 중요한 부분은 커스텀 에러 핸들러가 정규 표현식 컴파일 에러를 트랩 할 수 있다는 것입니다. 예외를 던지거나 잡을 필요가 없습니다. 나머지는 편리한 데모입니다.
나는 set_error_handler()를 사용하여 ErrorException을 던지는 함수를 등록합니다. preg_match()를 실행할 때 예외를 catch 한 다음 추적 정보를 사용하여 preg_match()를 실행하는 동일한 파일, 행 및 함수에서 예외가 발생했는지 확인합니다 (없는 경우 오류 또는 예외가 무언가에 의해 발생 함). 다른 함수 호출은 같은 줄에 있거나 PHP가 메모리가 부족한 것과 같습니다). 그런 다음 오류 메시지 만 사용자에게 출력합니다.
이 스크립트는 실제로 변수 함수를 사용하여 regex 함수를 실행합니다. 입력, 선행 및 후행 슬래시가없는 정규식, 수정자를 별도로 입력하십시오. 여기
전체 코드입니다 :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style type="text/css">
body {
font-family: monospace;
}
input[type=text], textarea {
letter-spacing: .25em;
font-weight: bold;
font-size: larger;
}
textarea {
width: 100%;
height: 25%;
}
fieldset {
display: inline;
}
.error {
color: red;
}
</style>
</head>
<body onload="document.getElementById('patterninput').focus();">
<?php
// Translate old-style PHP errors to OO approach
// http://www.php.net/manual/en/class.errorexception.php
function testRegexErrorHandler($errno, $errstr, $errfile, $errline, $errcontext) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
$pattern = isset($_REQUEST["pattern"]) ? $_REQUEST["pattern"] : "";
$mods = isset($_REQUEST["mods"]) ? $_REQUEST["mods"] : "";
$input = isset($_REQUEST["input"]) ? $_REQUEST["input"] : "";
$regex = "/$pattern/$mods";
$fns = array("match" => "preg_match", "matchall" => "preg_match_all");
$fnKey = isset($_REQUEST["function"]) ? $_REQUEST["function"] : "matchall";
$fn = isset($fns[$fnKey]) ? $fns[$fnKey] : "preg_match_all";
try {
set_error_handler("testRegexErrorHandler");
$result = $fn($regex, $input, $matches);
} catch (Exception $ex) {
// $ex is used later
}
restore_error_handler();
?>
<form action="" method="post">
<input type="text" size="100" id="patterninput" name="pattern" value="<?php echo htmlspecialchars($pattern); ?>" placeholder="Pattern" />
<input type="text" size="10" name="mods" value="<?php echo htmlspecialchars($mods); ?>" placeholder="Modifiers" />
<fieldset><legend>Function</legend>
<label for="fnmatch">preg_match()</label><input type="radio" name="function" value="match" id="fnmatch" <?php echo $fnKey == "match" ? "checked" : ""; ?> />
<label for="fnmatchall">preg_match_all()</label><input type="radio" name="function" value="matchall" id="fnmatchall" <?php echo $fnKey == "matchall" ? "checked" : ""; ?> />
</fieldset>
<input type="submit" name="submit" />
<textarea name="input" rows="10" placeholder="Input"><?php echo htmlspecialchars($input); ?></textarea>
</form>
<br/>
<?php
if(isset($ex)) {
$trace = $ex->getTrace();
if(is_array($trace) && isset($trace[1]) && is_array($trace[1])) {
$errFn = isset($trace[1]["function"]) ? $trace[1]["function"] : "";
$errLine = isset($trace[1]["line"]) ? $trace[1]["line"] : "";
$errFile = isset($trace[1]["file"]) ? $trace[1]["file"] : "";
if($errFn != "" && $errFn == $fn && $errLine != "" && $errLine == $ex->getLine() && $errFile != "" && $errFile == $ex->getFile() && get_class($ex) == "ErrorException") {
$regexErr = true;
}
}
if(empty($regexErr)) {
throw $ex;
} else {
echo "<p class=\"error\">The following error has occurred and is probably an error in your regex syntax:<br/>" .htmlspecialchars($ex->getMessage()) ."</p>\n\n";
}
}
// result will be unset if error or exception thrown by regex function
// such as if expression is syntactically invalid
if(isset($_REQUEST["submit"]) && isset($result)) {
echo "Result: $result<br/>\n";
echo "Matches:<pre>" .htmlspecialchars(print_r($matches, true)) ."</pre>\n\n";
}
?>
</body>
</html>
출처
2012-01-06 01:57:31
taz
'error_get_last()'충분합니다 :) – NullUserException