Get line number from preg_match_all()

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

    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á!

提交回复
热议问题