Test if a string is regex

后端 未结 4 1725
遥遥无期
遥遥无期 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:18

    The simplest way to test if a string is a regex is:

    if( preg_match("/^\/.+\/[a-z]*$/i",$regex))
    

    This will tell you if a string has a good chance of being intended to be as a regex. However there are many string that would pass that check but fail being a regex. Unescaped slashes in the middle, unknown modifiers at the end, mismatched parentheses etc. could all cause problems.

    The reason preg_last_error returned 0 is because the "invalid regex" is not:

    • PREG_INTERNAL_ERROR (an internal error)
    • PREG_BACKTRACK_LIMIT_ERROR (excessively forcing backtracking)
    • PREG_RECURSION_LIMIT_ERROR (excessively recursing)
    • PREG_BAD_UTF8_ERROR (badly formatted UTF-8)
    • PREG_BAD_UTF8_OFFSET_ERROR (offset to the middle of a UTF-8 character)

提交回复
热议问题