PHP比较两个文件路径以进行匹配preg_match

PHP比较两个文件路径以进行匹配preg_match,php,preg-match,filepath,Php,Preg Match,Filepath,我试图比较两个文件路径。 我从db查询接收文件路径,需要在.m3u文件中查找匹配项 我有以下代码,它不能正常工作。如果两个文件路径匹配,则将$contents数组中的索引作为指针返回 $searching = '/home/Music/Pink Floyd-Dark Side Of The Moon(MFSL Dr. Robert)/06 - Money.flac' $a_search = pathinfo( $searching ); $contents = file('/hom

我试图比较两个文件路径。 我从db查询接收文件路径,需要在.m3u文件中查找匹配项 我有以下代码,它不能正常工作。如果两个文件路径匹配,则将
$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;
                }
            }
        }
基本上,我需要比较两个文件路径,如果它们匹配,则返回
$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;
    }
}

为什么对要匹配的值使用
preg\u quote
?它只能用于正则表达式。这可能是不匹配的原因。