Search code examples
phpfilesearchglob

Find file by (similar) name PHP


I have a folder with songs, and the names of the files are: "Singer - Song"

I have a file with this name: "Example - A test song"

I want to find that file when I search for:

"Eample - A test song"

"Example - test song"

"eximple - A teste song"

Even if the search name has some errors, I want to find that file. How can I do it?


Solution

  • I wrote a short script by using PHP's similar_text function. It works for all strings written above.

    <?php
    $dir = $_SERVER['DOCUMENT_ROOT'];
    $needle = "eximple - A teste song";
    
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
                similar_text($file, $needle, $percent);
                if($percent > 80)
                    echo $file  . " similarity: " . $percent . "<br />";
            }
            closedir($dh);
        }
    }
    

    Explanation: The function calculates how much the two strings $file and $needle match (in percent). If they match more than 80% the file name is echoed. Feel free to adjust $needle and $dir to suit your needs.