在PHP中使用正则态度时,是否可以显示线号?
-
01-10-2019 - |
题
是否可以有一个正则搜索诸如' bfunction b'之类的字符串,它将显示匹配项的线号?
解决方案
我会建议一些可能对您有用的东西
// 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
}
其他提示
没有简单的方法可以做到,但是如果您愿意,您可以捕获比赛偏移(使用 PREG_OFFSET_CAPTURE
标志 preg_match
或者 preg_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\n
或者 <br>
(但这会更加棘手 <br />
或者 <br style="...">
, , ETC。)。
据我所知,这不是,但是如果您使用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);
opps!这不是JS!
不隶属于 StackOverflow