dongzi1397 2018-07-13 11:50
浏览 21
已采纳

preg_match来检索值

I'm using preg_match with PHP 5.6 to retrieve a value from a string. (I'm newb with preg_match)

It goes with this format:

data[SearchForm][somestringhere]

And I need to be able to retrieve the 'somestringhere' value.

I tried doing it this way:

$search_field_pattern   = "/\bdata[SearchForm][[a-zA-Z]]\b/i";
if(preg_match($search_field_pattern, "foo")) {
    debug('foobar!');
}

But it's not working. Can someone give me a hint why it's not working and what I should do to correctly approach this solution?

Thank you.

  • 写回答

1条回答 默认 最新

  • douwen3500 2018-07-13 11:57
    关注

    You may use

    $search_field_pattern  = "/\bdata\[SearchForm]\[(\w+)]/i";
    if(preg_match($search_field_pattern, "data[SearchForm][somestringhere]", $m)) {
        echo $m[1]; // => somestringhere
    }
    

    See the PHP demo

    The pattern matches

    • \b - a word boundary
    • data\[SearchForm]\[ - a literal string data[SearchForm][ (note [ are escaped to match literal [ chars)
    • (\w+) - capturing group 1: one or more word chars
    • ] - a ] char.

    The third argument to preg_match, $m, will hold the results. Since the necessary substring is captured into Group 1, the value is retrieved using $m[1].


    To get the last substring inside square brackets you may use
    if(preg_match("~\[(\w+)](?!.*\[\w+])~s", "data[SearchForm][somestringhere]", $m)) {
        echo $m[1]; // => somestringhere
    }
    

    See this PHP demo.

    To get the second one, use

    if(preg_match("~\[\w+].*?\[(\w+)]~s", "data[SearchForm][somestringhere]", $m)) {
        echo $m[1]; // => somestringhere
    }
    

    See yet another PHP demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 安装 opencv4nodejs 报错
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!