【发布时间】:2010-08-24 20:13:32
【问题描述】:
是否有可能有一个正则表达式正在搜索像 '\bfunction\b' 这样的字符串,它会显示找到匹配项的行号?
【问题讨论】:
标签: php regex line-numbers
是否有可能有一个正则表达式正在搜索像 '\bfunction\b' 这样的字符串,它会显示找到匹配项的行号?
【问题讨论】:
标签: php regex line-numbers
没有简单的方法可以做到这一点,但是如果您愿意,您可以捕获匹配偏移量(使用preg_match 或preg_match_all 的PREG_OFFSET_CAPTURE 标志),然后确定该位置在您的字符串中的哪一行通过计算在该点之前出现了多少换行符(例如)。
例如:
$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\n 或<br>(但这会有点棘手,因为您必须使用另一个正则表达式来解释<br /> 或 <br style="..."> 等)。
【讨论】:
我会建议一些可能对你有用的东西,
// 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
}
【讨论】:
据我所知不是这样,但如果你在 Linux 或其他类似 Unix 的系统上,grep 会这样做,并且可以使用(几乎)与preg_ 系列相同的正则表达式语法带有-P 标志的函数。
【讨论】:
没有。您可以将 PREG_OFFSET_CAPTURE 标志传递给 preg_match,女巫会告诉您以字节为单位的偏移量。但是,没有简单的方法可以将其转换为行号。
【讨论】:
这不是正则表达式,但有效:
$offset = strpos($code, 'function');
$lines = explode("\n", substr($code, 0, $offset));
$the_line = count($lines);
哎呀!这不是js!
【讨论】: