How to search a substring within text file and print the whole line in PHP

1 Answer

0 votes
$file = 'data.txt';
$searchword = 'regular expression';

$content = file_get_contents($file);

$pattern = preg_quote($searchword, '/');

$pattern = "/(?i)^.*$pattern.*\$/m";
if (preg_match_all($pattern, $content, $matches)) {
	echo "<pre>";
	print_r($matches[0]);
	echo "</pre>";
} else {
	echo "Not found";
}
 
 
/*
 
data.txt
--------
Perform a php Regular Expression match
that is especially suited to web development.
Searches subject for a match to the regular expression
At least one element will be present within the array
component doesn't exist
Perform a global regular expression match
produced by The PHP Group
Split string by a REGULAR EXPRESSION
 
*/
 
 
/*
run:
 
Array
(
    [0] => Perform a php Regular Expression match
    [1] => Searches subject for a match to the regular expression
    [2] => Perform a global regular expression match
    [3] => Split string by a REGULAR EXPRESSION
)
 
*/

 



answered Aug 22, 2020 by avibootz

Related questions

1 answer 218 views
1 answer 206 views
1 answer 198 views
1 answer 172 views
3 answers 263 views
...