Get line number from preg_match_all()

前端 未结 10 943
天命终不由人
天命终不由人 2021-02-07 09:23

I\'m using PHP\'s preg_match_all() to search a string imported using file_get_contents(). The regex returns matches but I would like to know at which line number those matches a

10条回答
  •  盖世英雄少女心
    2021-02-07 09:53

    Using preg_match_all with the PREG_OFFSET_CAPTURE flag is necessary to solve this problem, the code comments should explain what kind of array preg_match_all returns and how the line numbers can be calculated:

    // Given string to do a match with
    $string = "\n\nabc\nwhatever\n\ndef";
    
    // Match "abc" and "def" in a string
    if(preg_match_all("#(abc).*(def)#si", $string, $matches, PREG_OFFSET_CAPTURE)) {
      // Now $matches[0][0][0] contains the complete matching string
      // $matches[1][0][0] contains the results for the first substring (abc)
      // $matches[2][0][0] contains the results for the second substring (def)
      // $matches[0][0][1] contains the string position of the complete matching string
      // $matches[1][0][1] contains the string position of the first substring (abc)
      // $matches[2][0][1] contains the string position of the second substring (def)
    
      // First (abc) match line number
      // Cut off the original string at the matching position, then count
      // number of line breaks (\n) for that subset of a string
      $line = substr_count(substr($string, 0, $matches[1][0][1]), "\n") + 1;
      echo $line . "\n";
    
      // Second (def) match line number
      // Cut off the original string at the matching position, then count
      // number of line breaks (\n) for that subset of a string
      $line = substr_count(substr($string, 0, $matches[2][0][1]), "\n") + 1;
      echo $line . "\n";
    }
    

    This will return 3 for the first substring and 6 for the second substring. You can change \n to \r\n or \r if you use different newlines.

提交回复
热议问题