2

是否有可能有一个正则表达式正在搜索像 '\bfunction\b' 这样的字符串,它将显示找到匹配项的行号?

4

5 回答 5

4

没有简单的方法可以做到这一点,但是如果您愿意,您可以捕获匹配偏移量(使用or的PREG_OFFSET_CAPTURE标志),然后通过计算之前出现的换行数(例如)来确定该位置在字符串中的哪一行观点。preg_matchpreg_match_all

例如:

$matches = array();
preg_match('/\bfunction\b/', $string, $matches, PREG_OFFSET_CAPTURE);
list($capture, $offset) = $matches[0];
$line_number = substr_count(substr($string, 0, $offset), "\n") + 1; // 1st line would have 0 \n's, etc.

根据应用程序中“行”的构成,您可能会交替搜索\r\nor <br>(但这会有点棘手,因为您必须使用另一个正则表达式来解释<br />or<br style="...">等​​)。

于 2010-08-24T20:22:17.517 回答
1

据我所知不是,但如果你在 Linux 或其他类似 Unix 的系统上,grep会这样做并且可以使用(几乎)与带有标志preg_的函数系列相同的正则表达式语法。-P

于 2010-08-24T20:16:17.187 回答
1

不,您可以将 PREG_OFFSET_CAPTURE 标志传递给 preg_match,女巫会告诉您偏移量(以字节为单位)。但是,没有简单的方法可以将其转换为行号。

于 2010-08-24T20:20:54.213 回答
1

我会建议一些可能对你有用的东西,

// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    // do the regular expression or sub string search here
}
于 2010-08-24T20:25:46.090 回答
0

这不是正则表达式,但有效:

$offset = strpos($code, 'function');
$lines = explode("\n", substr($code, 0, $offset));
$the_line = count($lines);

哎呀!这不是js!

于 2010-08-24T20:36:59.710 回答