duanshan3331 2017-07-27 09:41
浏览 348
已采纳

使用正则表达式在字符串中获取两个匹配项[重复]

This question already has an answer here:

My string:

fields[name_1]

I want to get fields and name_1 using regex.

I'm know about preg_match_all(), but I'm not friends with regular expressions.

</div>
  • 写回答

2条回答 默认 最新

  • dto52236 2017-07-27 09:44
    关注

    This can be used for direct match:

    $string = 'fields[name_1]';
    
    preg_match('/(.+)\[(.+)\]/', $string, $matches);
    
    print_r($matches);
    

    You get:

    Array
    (
        [0] => fields[name_1]
        [1] => fields
        [2] => name_1
    )
    

    So, $matches[1] and $matches[2] are what you needed.


    Still I am unclear about your exact need!


    Here are the explanation for the Regex:

    1. https://regex101.com/r/PcJzQL/3
    2. http://www.phpliveregex.com/
    3. https://www.functions-online.com/preg_match.html
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?