我正在使用 PHP 的 preg_match_all() 搜索使用 file_get_contents() 导入的字符串。正则表达式返回匹配项,但我想知道在哪个行号找到了这些匹配项。实现这一目标的最佳技术是什么?
我可以将文件作为数组读取并为每一行执行正则表达式,但问题是我的正则表达式匹配回车符(新行)的结果。
最佳答案
好吧,有点晚了,也许你已经解决了这个问题,但我不得不这样做,而且相当简单。
在 preg_match
中使用 PREG_OFFSET_CAPTURE
标志将返回匹配的字符位置。
让我们假设$charpos,所以
list($before) = str_split($content, $charpos); // fetches all the text before the match
$line_number = strlen($before) - strlen(str_replace("\n", "", $before)) + 1;
瞧!
关于php - 从 preg_match_all() 获取行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4730867/