【问题标题】:PHP: string to regexPHP:字符串到正则表达式
【发布时间】:2012-03-26 13:35:33
【问题描述】:

我尝试使用字符串作为正则表达式模式,但出现以下错误

PHP Warning:  preg_match(): Unknown modifier '>' in /Applications/MAMP/htdocs/cruncher/Plugins/wordpress/WPDetect.php on line 22
PHP Warning:  preg_match(): Unknown modifier '/' in /Applications/MAMP/htdocs/cruncher/Plugins/wordpress/WPDetect.php on line 22

代码

$str = "<meta name=\"generator\" content=\"WordPress.com\" />"
preg_match("/".$str."/", $content->content)

我也尝试使用preg_quote 函数,但我遇到了类似的问题。

什么是让它工作的正确方法?

苏丹

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    使用preg_quote 函数和|...| 括起来的模式

    preg_match("|" . preg_quote($str, "|") . "|", $content->content)
    

    【讨论】:

    • 好吧抱歉不知道有时间限制:)
    • 一旦$str 包含|,这将失败。我的建议是总是提供第二个参数。在这种情况下:'|'.preg_quote($str, '|').'|'
    【解决方案2】:

    这对我有用

    $pattern = "/" . preg_quote($source, "/") . "/";
    

    【讨论】:

      【解决方案3】:

      你必须摆脱你的限制器

      $str = "<meta name=\"generator\" content=\"WordPress.com\" \/>"
      

      【讨论】:

        【解决方案4】:

        正则表达式包含一组特殊字符,如 \ - * 。 ? $ ^ + () [] 等等,你必须在使用它之前将它们从你的字符串中转义(你通过在字符之前添加一个 \ 来逃避)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多