【问题标题】:preg_match problempreg_match 问题
【发布时间】:2010-05-04 17:43:44
【问题描述】:

我正在尝试从 php 中的字符串中获取一些东西。在 RegexBuddy 和正则表达式测试器(firefox 插件)中效果很好,但是 php 给了我以下内容:

警告:preg_match() [function.preg-match]:编译 失败:不匹配的括号在 偏移 34 英寸 D:\路径\example.php 在第 62 行

我的模式是"/.{4}_tmp\\([A-Za-z0-9.\\]*)\(([0-9]*)\) : (.*)/i"

示例字符串:C:\Temp\browseide\projects\32\821C_tmp\SourceFiles\main.c(8) : error C2143: syntax error : missing ';' before 'for'

RegexBuddy 得到什么:

821C_tmp\SourceFiles\main.c(8) : error C2143: syntax error : missing ';' before 'for'
Group 1:    SourceFiles\main.c
Group 2:    8
Group 3:    error C2143: syntax error : missing ';' before 'for'

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    您需要对 PHP 字符串中的反斜杠进行转义:

    "/.{4}_tmp\\\\([A-Za-z0-9.\\\\]*)\\(([0-9]*)\\) : (.*)/i"
    

    【讨论】:

    • 没有必要在末尾加倍`\\` - PHP没有特殊的\(\)所以它不需要被转义......没有伤害或者,只是觉得值得一提。
    【解决方案2】:

    一旦 PHP 字符串解析了你最终得到的字符串,你需要再次转义反斜杠:

    /.{4}_tmp\([A-Za-z0-9.\]*)\(([0-9]*)\) : (.*)/i
    

    试试echo "/.{4}_tmp\\([A-Za-z0-9.\\]*)\(([0-9]*)\) : (.*)/i";

    如果你想在模式中使用\\,你应该在双引号内加上\\\\

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多