Get line number from preg_match_all()

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

    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.

提交回复
热议问题