Agung Kahono
Agung Kahono

Reputation: 13

how to search files in a directory using 2 words in php

In mydirectory

green.txt
black.txt
shadow.txt

and my php code

<?php
$key = "black+shadow"
$dir = 'file/dir';
$ext = '.txt';
$i=0;
$search = $key;
$results = glob("$dir/*$search*$ext");
if(count($results) != 1) {
    foreach($results as $item) {
      echo $item;
    }
  }?>

I want to get the output "black.txt" and "shadow.txt"

Upvotes: 0

Views: 95

Answers (2)

user10226920
user10226920

Reputation:

<?php
$key = "{black,shadow}";
$ext = '.txt';
$i=0;
$search = $key;
$results = glob("$search*$ext",GLOB_BRACE);
if(count($results) != 1) {
    foreach($results as $item) {
      echo $item;
    }
  }?>

per the manual,

GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'

i added braces around your search terms and added the GLOB_BRACE flag. (dir removed as i ran a local test)

Upvotes: 1

Aaron Saray
Aaron Saray

Reputation: 1177

$key = "black+shadow";
$dir = "file/dir"
$ext = '.txt';

foreach (explode("+", $key) as $filePart) {
    $fileName = $filePart . $ext;
    if (file_exists("{$dir}/{$fileName}")) {
        echo $fileName . '<br>';
    }
}

This assumes that the pattern will always be filepart separated by +

You can use glob if you end up with more complex solutions - but this is probably the fastest and easiest way to understand IMHO.

Upvotes: 1

Related Questions