2013-01-10 61 views
0

可能重複:
Test if a regular expression is a valid one in PHP如何檢查給定的字符串是否有效正則表達式?

<?php 

    $subject = "PHP is the web scripting language of choice.";  
    $pattern = 'sssss'; 

    if(preg_match($pattern,$subject)) 
    { 
     echo 'true'; 
    } 
    else 
    { 
     echo 'false'; 
    } 

?> 

上面的代碼給我警告,因爲串$pattern不是有效的正則表達式。

如果我通過有效的正則表達式,然後它工作正常.....

我怎麼能檢查$pattern是有效的正則表達式?

+0

在這裏看到正確的:http://stackoverflow.com/questions/7095238/an-invalid-regex-pattern –

+1

,或者更好,這裏:http://stackoverflow.com/questions/362793/regexp-that-matches-valid-regexps – k102

+0

或這一個:http://stackoverflow.com/questions/8825025/test-if-a-regular-expression-是一個有效的一個在PHP –

回答

-1

你可以只是包裝preg_match與嘗試捕捉,並考慮導致假的,如果它拋出異常。

無論如何,你可以看看regular expression to detect a valid regular expression

+2

在函數之前添加'@'來抑制警告/錯誤是不好的做法。它會隱藏你的代碼中可能存在的錯誤。 –

-1

使用===操作:

<?php 

    $subject = "PHP is the web scripting language of choice.";  
    $pattern = 'sssss'; 

    $r = preg_match($pattern,$subject); 
    if($r === false) 
    { 
     // preg matching failed (most likely because of incorrect regex) 
    } 
    else 
    { 
     // preg match succeeeded, use $r for result (which can be 0 for no match) 
     if ($r == 0) { 
      // no match 
     } else { 
      // $subject matches $pattern 
     } 
    } 

?> 
+0

這不是什麼OP要求。你的代碼會導致語法錯誤。 – F0G

+0

我修正了語法錯誤(複製粘貼錯誤的情況)。我的回答給出了一種檢測正則表達式是否不正確的方法(這是OP要求的)。 –

+0

'preg_match($ pattern,$ subject)'會導致語法錯誤,因爲'$ pattern'是無效的RegEx。 – F0G

5

如果Regexp出現問題,您可以編寫一個引發錯誤的函數。 (像它應該在我看來。) 使用@來壓制警告是不好的做法,但如果你用一個拋出的異常替換它應該沒問題。

function my_preg_match($pattern,$subject) 
{ 
    $match = @preg_match($pattern,$subject); 

    if($match === false) 
    { 
     $error = error_get_last(); 
     throw new Exception($error['message']); 
    } 
    return false; 
} 

那麼你可以檢查正則表達式是

$subject = "PHP is the web scripting language of choice.";  
$pattern = 'sssss'; 

try 
{ 
    my_preg_match($pattern,$subject); 
    $regexp_is_correct = true; 
} 
catch(Exception $e) 
{ 
    $regexp_is_correct = false; 
} 
相關問題