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.

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

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀