|
|
To search for text within files in a directory and its subdirectories recursively using PHP, you can employ a function that utilizes
RecursiveDirectoryIterator and RecursiveIteratorIterator. This approach provides a robust and efficient way to traverse the file system. |
$searchDirectory = 'cache'; // Replace with the actual directory pathChange the keyword/Text that you want to search from directory at line 30
$textToFind = 'html'; // Replace with the text you want to findHere is completed full code that you can use in your php file.
<?php
function searchFilesRecursively(string $directory, string $searchText): array
{
$results = [];
try {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$filePath = $file->getPathname();
$fileContents = file_get_contents($filePath);
if ($fileContents !== false && strpos($fileContents, $searchText) !== false) {
$results[] = $filePath;
}
}
}
} catch (UnexpectedValueException $e) {
// Handle cases where the directory might not exist or is not readable
error_log("Error accessing directory: " . $e->getMessage());
}
return $results;
}
// Usage example:
$searchDirectory = 'cache'; // Replace with the actual directory path
$textToFind = 'html'; // Replace with the text you want to find
$foundFiles = searchFilesRecursively($searchDirectory, $textToFind);
if (!empty($foundFiles)) {
echo "Text found in the following files:\n";
foreach ($foundFiles as $file) {
echo "- " . $file . "\n";
}
} else {
echo "Text not found in any files within the specified directory.\n";
}
?>
| php function |
Type: | Develop |
Category: | Web Tutorial |
Sub Category: | PHP Function Tutorial |
Uploaded by: | Admin |