PHP 比较两个文件路径是否匹配 preg_match

PHP Compare two filepaths for match preg_match

我正在尝试比较两个文件路径。 我从数据库查询中收到文件路径,我需要在 .m3u 文件中找到匹配项 我有以下代码无法正常工作。如果两个文件路径匹配,则 return 来自 $contents 数组的索引作为指针。

 $searching = '/home/Music/Pink Floyd-Dark Side Of The Moon(MFSL Dr. Robert)/06 - Money.flac'
 $a_search = pathinfo( $searching ); 

 
 $contents = file('/home/playlist/music.m3u'); 

 foreach( $contents as $index => $line ) {
            
            $a_line = pathinfo( $line );
            
            $searchbasename = preg_quote($a_search['dirname'] );
            $linebasename   = preg_quote($a_line['dirname'] );

            if( array_key_exists('dirname', $a_line)){
                if (preg_match("/\b$searchbasename\b/", $linebasename)) {
                   return $index;
                }
            }
        }

基本上,我需要比较两个文件路径,如果它们匹配,return $contents 数组的索引。

提前感谢您的宝贵时间。

.m3u 文件的一部分

/home/scott/Music/U2/U2 - War [FLAC]/03 - New Year's Day.flac
/home/scott/Music/U2/U2 - The Unforgettable Fire [FLAC]/02.Pride.flac
/home/scott/Music/ZZ Top/(1972) ZZ Top - Rio Grande Mud/02 Just Got Paid.flac
/home/scott/Music/ZZ Top/(1981) ZZ Top - El Loco/08 Groovy Little Hippie Pad.flac
/home/scott/Music/ZZ Top/(1979) ZZ Top - Deguello/01 I Thank You.flac
/home/scott/Music/ZZ Top/(1973) ZZ Top - Tres Hombres/03 Beer Drinkers & Hell Raisers.flac
/home/scott/Music/ZZ Top/(1976) ZZ Top - Tejas/02 Arrested for Driving While Blind.flac
/home/scott/Music/ZZ Top/(1983) ZZ Top - Eliminator/08 TV Dinners.flac
/home/scott/Music/ZZ Top/(1973) ZZ Top - Tres Hombres/02 Jesus Just Left Chicago.flac
/home/scott/Music/ZZ Top/(1979) ZZ Top - Deguello/04 A Fool For Your Stockings.flac
/home/scott/Music/ZZ Top/(1979) ZZ Top - Deguello/03 I'm Bad, I'm Nationwide.flac
/home/scott/Music/ZZ Top/(1981) ZZ Top - El Loco/01 Tube Snake Boogie.flac

在我看来,您无法匹配整个目录路径。相反,您想要匹配后跟 flac 文件名的专辑目录。换句话说,你想匹配最后一个目录和文件名作为一个字符串。

您可以分解、切片并重新加入文件路径的各个部分,但我更喜欢使用正则表达式在一次调用中提取子字符串。我的 preg_replace() 调用将删除除最终目录和文件名之外的所有字符。

$searching = '/home/Music/Pink Floyd-Dark Side Of The Moon(MFSL Dr. Robert)/06 - Money.flac';
$needle = preg_replace('~/(?:[^/]*/)*(?=[^/]*/[^/]*$)~', '', $searching);
// or     implode('/', array_slice(explode('/', $searching), -2)); // ...if you don't like regex

foreach(file('/home/playlist/music.m3u') as $index => $line) {
    if (strpos($line, $needle) !== false) {
        return $index;
    }
}