如何检查给定字符串是否有效正则表达式?

use*_*396 1 php

可能重复:
测试PHP中的正则表达式是否为有效表达式

 <?php 

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

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

?>
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我警告,因为字符串$pattern不是有效的正则表达式.

如果我传递有效的正则表达式,那么它工作正常.....

我如何检查$pattern是有效的正则表达式?

Arc*_*ron 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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以检查正则表达式是否正确

$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;
}
Run Code Online (Sandbox Code Playgroud)