Get line number from preg_match_all()

前端 未结 10 938
天命终不由人
天命终不由人 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:59

    Late to the game but I needed this functionality today and I realized that @Javier's and @iguito's answers could be combined into a simple solution. I also replaced the check for \n with PHP_EOL for my use case:

    // Get your matches
    preg_match_all( '[YOUR REGEX HERE]', $data, $matches, PREG_OFFSET_CAPTURE );
    
    // This is my loop format, yours may need to be different
    foreach ( $matches[0] as $match ) {
    
        // Get the line number for the current match 
        list( $before ) = str_split( $data, $match[1] );
        $line_number = substr_count( $before, PHP_EOL ) + 1;
        echo $line_number;
    
    }
    

提交回复
热议问题