2010-08-21 4 views
6

rubular과 비슷한 서비스를 설정하려고하지만 PHP가 preg 계열의 함수를 사용하여 언어로 설정하려고합니다. 입력 정규식, 테스트 문자열을 취하고 preg_match()을 실행합니다.정규 표현식 컴파일 오류 캡처

컴파일 오류가 발생했는지 (예 : 잘못된 정규식) 어떻게 알 수 있습니까? 그렇다면 오류는 무엇입니까? 일반적으로이 같은 경고를 발생합니다 : 정규식 컴파일 실패 할 경우 0 (PREG_NO_ERROR)을 반환하기 때문에

Warning: preg_match() [function.preg-match]: Compilation failed: missing) at offset x in ****** on line y 

pcre_last_error()가 여기 완전히 쓸모가 없다.

경고를 캡처하기 위해 출력 버퍼링을 사용하는 것이 하나의 옵션이지만 더 좋은 방법이 있어야합니다.

답변

2

가장 좋은 방법은 @이라는 오류 메시지를 생략하고 반환 값을 확인한 다음 false 인 경우 error_get_last으로 전화하는 것입니다.

pcre_compile 주위에 나만의 래퍼를 작성할 수도 있습니다. 에러 코드와 문자열의 저장을위한 포인터를받습니다. 너무 어려워서는 안됩니다. preg_match은 얇은 래퍼입니다.

+0

'error_get_last()'충분합니다 :) – NullUserException

0

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>