Get line number from preg_match_all()

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

    You can use preg_match_all to find offsets of every linefeed and then compare them against the offsets you already have.

    // read file to buffer
    $data = file_get_contents($datafile);
    
    // find all linefeeds in buffer    
    $reg = preg_match_all("/\n/", $data, $lfall, PREG_OFFSET_CAPTURE );
    $lfs = $lfall[0];
    
    // create an array of every offset
    $linenum = 1;
    $offset = 0;    
    foreach( $lfs as $lfrow )
    {
        $lfoffset = intval( $lfrow[1] );
        for( ; $offset <= $lfoffset; $offset++ )
            $offsets[$offset] = $linenum;   // offset => linenum
        $linenum++;
    }
    

提交回复
热议问题