![]() |
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. |
Example:
PHP
$searchDirectory = 'cache'; // Replace with the actual directory path
Change the keyword/Text that you want to search from directory at line 30
$textToFind = 'html'; // Replace with the text you want to find
Here is completed full code that you can use in your php file.
Example:
PHP
<?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 |
How to create title to url/slug in PHP | PHP Function Tutorial |
How to minify all html in a single line with PHP | PHP Function Tutorial |
How to add a url with php_curl fuctionally cURL | PHP Function Tutorial |
How to search file directory with text recursive in PHP | PHP Function Tutorial |
Type
: |
Develop |
Category
: |
Web Tutorial |
Sub Category
: |
PHP Function Tutorial |
Uploaded by
: |
Admin |