PHP Snippet 1:
<?php
$file = 'somefile.txt';
$searchfor = 'name';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if (preg_match_all($pattern, $contents, $matches))
{
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else
{
echo "No matches found";
}
PHP Snippet 2:
<?php
$searchthis = "mystring";
$matches = array();
$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
//show results:
print_r($matches);
?>
PHP Snippet 3:
<?php
// What to look for
$search = 'foo';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
}
PHP Snippet 4:
<?php
$search = 'foo';
$lines = file('file.txt');
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
{
$found = true;
echo $line;
}
}
// If the text was not found, show a message
if(!$found)
{
echo 'No match found';
}
PHP Snippet 5:
$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];
PHP Snippet 6:
if (isset($_GET["keyword"])){
foreach(glob('*.php') as $file) {
$searchfor = $_GET["keyword"];
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo $file. "\n";
echo implode("\n", $matches[0]);
echo "\n\n";
}
else{
// echo "No matches found";
}
}
}