Find string and get line number in a file using PHP

Today’s lesson is an interesting one and not often discussed by many. PHP script to find a string in a file and return the line numbers.

I have written this PHP script as a function, so you can easily integrate with your existing code,

Here is the find_line_number_by_string($filename, $search, $case_sensitive) function:

Basically this function has three parameters,

Required parameters:
1. $filename => give the filename with exact path and extension (eg. ‘folder/filename.html’)
2. $search => give your search string /text / number (‘mystring’)

Optional Parameter:
3. $case_sensitive => by default this is false, means all cases converted to lower, if you wish to match exact case then make this true


How to use this function?

Here is the usage of the above code:

Output (if string matches):

String(s) found in 38,61

Output (if string not matched):

No match found


See the example.html file here:

See the Demo here or just Download the code so you can play around with it:

demo download



Related Posts

Leave a Reply