PHP regex groups captures

后端 未结 4 2053
南旧
南旧 2020-12-06 16:34

I have the following regex:

\\[([^ -\\]]+)( - ([^ -\\]]+))+\\]

This match the following successfully:

[abc - def - ghi - jk         


        
相关标签:
4条回答
  • 2020-12-06 17:03

    This is not the job for the regexp. Match against \[([^\]]*)\], then split the first capture by the " - ".

    <?php                                                                       
      $str = "[abc - def - ghi - jkl]";
      preg_match('/\[([^\]]*)\]/', $str, $re);
      $strs = split(' - ', $re[1]);
      print_r($strs);
    ?>
    
    0 讨论(0)
  • 2020-12-06 17:04

    To group your matches, use parenthesize. EG:

    $string = 'bob';
    preg_match('/bob/', $string, $matches);
    

    $matches will be ['bob']

    preg_match('/(b)(o)(b)/', $string, $matches);
    

    $matches will be ['bob','b','o','b']

    0 讨论(0)
  • 2020-12-06 17:13

    SPL preg_match_all will return regex groups starting on index 1 of the $matches variable. If you want to get only the second group you can use $matches[2] for example.

    Syntax:

    $matches = array(); 
    preg_match_all(\
        '/(He)\w+ (\w+)/', 
        "Hello world\n Hello Sunshine", 
        $matches
    ); 
    var_dump($matches);
    

    Result:

    array(3) {
      [0] =>
      array(2) {
        [0] =>
        string(11) "Hello world"
        [1] =>
        string(14) "Hello Sunshine"
      }
      [1] =>
      array(2) {
        [0] =>
        string(2) "He"
        [1] =>
        string(2) "He"
      }
      [2] =>
      array(2) {
        [0] =>
        string(5) "world"
        [1] =>
        string(8) "Sunshine"
      }
    }
    

    P.S. This answer is posted for the context of the question title after being directed here by a Google search. This was the information I was interested in when searching for this topic.

    0 讨论(0)
  • 2020-12-06 17:14

    Assuming the tokens in your sample string never contain spaces, and are alphanumeric:

    <?php
        $pattern = "/([\w|\d])+/";
        $string = "[abc - 123 - def - 456 - ghi - 789 - jkl]";
        preg_match_all($pattern, $string, $matches);
        print_r($matches[0]);
    ?>
    

    Output:

    Array
    (
        [0] => abc
        [1] => 123
        [2] => def
        [3] => 456
        [4] => ghi
        [5] => 789
        [6] => jkl
    )
    
    0 讨论(0)
提交回复
热议问题