Get line number from preg_match_all()

well it's kinda late, maybe you alrady solved this, but i had to do it and it's fairly simple. using PREG_OFFSET_CAPTURE flag in preg_match will return the character position of the match. lets assume $charpos, so

list($before) = str_split($content, $charpos); // fetches all the text before the match

$line_number = strlen($before) - strlen(str_replace("\n", "", $before)) + 1;

voilá!


You can't do this with only regexs. At least not cleanly. What can you do it to use the PREG_OFFSET_CAPTURE flag of the preg_match_all and do a post parsing of the entire file.

I mean after you have the array of matches strings and starting offsets for each string just count how many \r\n or \n or \r are between the beginning of the file and the offset for each match. The line number of the match would be the number of distinct EOL terminators (\r\n | \n | \r) plus 1.

Tags:

Php

Regex