开发者

Is it possible to show line numbers when using a regex in PHP?

Is it possible to have a regex that is searching for a string like '\bfunction\b' that will displ开发者_开发知识库ay the line number where it found the match?


There's no simple way to do it, but if you wanted to, you could capture the match offset (using the PREG_OFFSET_CAPTURE flag for preg_match or preg_match_all) and then determine which line that location is in your string by counting how many newlines (for example) occur before that point.

For example:

$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.

Depending on what constitutes a "line" in your application, you might alternately want to search for \r\n or <br> (but that would be a bit more tricky because you'd have to use another regex to account for <br /> or <br style="...">, etc.).


I will suggest something that might work for you,

// 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
}


So far as I know it's not, but if you're on Linux or some other Unix-like system, grep will do that and can use (nearly) the same regular expression syntax as the preg_ family of functions with the -P flag.


No. You can pass the PREG_OFFSET_CAPTURE flag to preg_match, witch will tell you the offset in bytes. However, there is no easy way to convert this to a line number.


This is not regex, but works:

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

Opps! This is not js!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜