Get line number from preg_match_all()

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

    $data = "Abba
    Beegees
    Beatles";
    
    preg_match_all('/Abba|Beegees|Beatles/', $data, $matches, PREG_OFFSET_CAPTURE);
    foreach (current($matches) as $match) {
        $matchValue = $match[0];
        $lineNumber = substr_count(mb_substr($data, 0, $match[1]), PHP_EOL) + 1;
    
        echo "`{$matchValue}` at line {$lineNumber}\n";
    }
    

    Output

    `Abba` at line 1
    `Beegees` at line 2
    `Beatles` at line 3
    

    (check your performance requirements)

提交回复
热议问题