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
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;
}