在目录中按名称搜索特定文件

I am creating a function for search only files inside directories and inside the folder if there is, using the recursive method. I need to list the all the files matching to my keyword. I list the all the files inside the directory and trying to match the filename to my search key, that's how I am thinking to search file, I don't know it is the correct way, even though i can list the files but the search part not working,

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      $key = trim($_POST['search']);
      $path = BOOKROOT;

      if (isset($key)) {
          $books = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
          $data = array();

          foreach ($books as $book) {
              if ($book->isDir()) {
                  continue;
              }

              if ($key == $book->getFilename()) {
                  $data[] = $book->getFilename();
              }
          }
            // Load view
            $this->view('books/searchpdf', $data);
      }
}

In the line that you compare the name with the key, you can replace with

if(strpos($book->getFilename(), $key) !== false) {

You can search file in directory like:

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "
";
}
?>