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

1 Answer

0 votes
$file = 'data.txt';
$searchword = 'php';

$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
--------

PHP is a general-purpose scripting language
that is especially suited to web development.
It was originally created by Danish-Canadian programmer
Rasmus Lerdorf in 1994
the PHP reference implementation is now
produced by The PHP Group

*/


/*
run:

Array
(
    [0] => PHP is a general-purpose scripting language
    [1] => the PHP reference implementation is now
    [2] => produced by The PHP Group
)

*/

 



answered Aug 22, 2020 by avibootz

Related questions

1 answer 187 views
1 answer 201 views
1 answer 164 views
1 answer 210 views
1 answer 178 views
...