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:

function find_line_number_by_string($filename, $search, $case_sensitive=false ) {
		$line_number = '';
		if ($file_handler = fopen($filename, "r")) {
		   $i = 0;
		   while ($line = fgets($file_handler)) {
			  $i++;
			  //case sensitive is false by default
  			  if($case_sensitive == false) {	
				$search = strtolower($search);  //convert file and search string
				$line = strtolower($line); 		//to lowercase
			  }
			  //find the string and store it in an array
			  if(strpos($line, $search) !== false){
				$line_number .=  $i.",";
			  }
		   }
		   fclose($file_handler);
		}else{
			return "File not exists, Please check the file path or filename";
		}
		//if no match found
		if(count($line_number)){
			return substr($line_number, 0, -1);
		}else{
			return "No match found";
		}
	}

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:

<?php 

$output = find_line_number_by_string('example.html', 'materials');
	
print "String(s) found in ".$output;

?>

Output (if string matches):

String(s) found in 38,61

Output (if string not matched):

No match found

 

See the example.html file here: http://www.tutorialsmade.com/demo/find_line_number/example.html


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

demo download

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top