How to check if a given string is valid Regex?

Possible Duplicate:
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';
    }

?>

The above code gives me warning because the string $pattern is not a valid regular expression.

If I pass valid regular expression then it works fine.....

How can i check $pattern is valid regular expression?


You can just wrap preg_match with try catch, and consider result false, if it throws exception.

Anyway, you can take a look at regular expression to detect a valid regular expression.


You could write a function that throws an error if there is something wrong with the Regexp. (Like it should have been in my opinion.) It is bad practice to use the @ to suppress warnings, but if you replace it with a thrown exception it should be ok.

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;
}

then you can check if the regexp is correct with

$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;
}

使用===运算符:

<?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
        }
    }

?>
链接地址: http://www.djcxy.com/p/76750.html

上一篇: 如何用PHP验证正则表达式

下一篇: 如何检查给定的字符串是否有效正则表达式?