Search code examples
phpregexline-numbers

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 display the line number where it found the match?


Solution

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