Test if a string is regex

后端 未结 4 1733
遥遥无期
遥遥无期 2020-12-03 13:50

Is there a good way of test if a string is a regex or normal string in PHP?

Ideally I want to write a function to run a string through, that returns true or false.

4条回答
  •  不知归路
    2020-12-03 14:13

    Why not just use...another regex? Three lines, no @ kludges or anything:

    // Test this string
    $str = "/^[A-Za-z ]+$/";
    
    // Compare it to a regex pattern that simulates any regex
    $regex = "/^\/[\s\S]+\/$/";
    
    // Will it blend?
    echo (preg_match($regex, $str) ? "TRUE" : "FALSE");
    

    Or, in function form, even more pretty:

    public static function isRegex($str0) {
        $regex = "/^\/[\s\S]+\/$/";
        return preg_match($regex, $str0);
    }
    

    This doesn't test validity; but it looks like the question is Is there a good way of test if a string is a regex or normal string in PHP? and it does do that.

提交回复
热议问题