2013-01-10 65 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; 
} 
相关问题