views:

55

answers:

5

I was just wondering if it is possible to have a regex that is searching for a string like '\bfunction\b' that will display the line number where it found the match?

+1  A: 

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.

Jeremy DeGroot
+1  A: 

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.

Sjoerd
When you have the offset, you can count the number of new lines up to it.
Majid
+2  A: 

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

Daniel Vandersluis
+1  A: 

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
}
aromawebdesign.com
A: 

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!

Majid