regex - PHP: Find keywords recursively in files and return surrounding context as well as filename


Interesting problem: I search a pile of files and directories for a keyword and my function returns me the filenames as an Array:

$files = array();

function search_in_dir($dir, $str) {
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $filename) {
        $files[] = $filename;

    foreach ($files as $k => $file) {
        $source = file_get_contents($file);
        if (strpos($source, $str) === false) {
    return array_filter($files);

$filenamesWithPaths = search_in_dir("/home/Documents", "testKeyword");

The variable$filenamesWithPaths contains now an array of the Filenames and the paths. However what I ultimately want to achieve is an associative array or some collection containing the paths with filenames as well as the surrounding text (which is in my case HTML code).

It would be imagineable to return the whole line where the keyword was found and I then further trim it down with other instructions.




Ok so, file() — Reads entire file into an array

You can iterate through each item in a foreach and find your matches.

If the index is 23, it's on line 24. Simple as that and build your output array how you please.




Since the Stackoverflow community strongly advises to avoid php for searching functionalities I will use find, which beats grep in performance

$search = 'find ' . $directory . ' -type f -exec grep -r ' . $keyword . ' {} + '

Store the path+filenames and surrounding context into an collection in php would be the next step. However this is somehow not working:

$RESULT = shell_exec('find ' . $domain . ' -type f -exec grep -r ' . $keyword . ' {} + ');

$arr = explode('/index.html:', $RESULT);

How to retrieve the path and surrounding context now; as in how to best parse the grep output?

People are also looking for solutions to the problem: php - Symfony2 - Inject a service into SonataAdmin


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.