John Davidson

PHP Compare two filepaths for match preg_match

0 comments
Message:


I am trying to compare two filepaths.
I receive the filepath from a db query, and I need to find in the .m3u file for a match
I have the following code which is not working properly. If the two filepaths are a match, then return the index from the $contents array as a pointer.


 $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;
}
}
}

Basically, I need to compare two filepaths, and if they match, return the index of the $contents array.


Thanks in advance, for your time.


A portion of the .m3u file


/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


My Answer:
You can try the following code to compare two filepaths and return the index of the $contents array if they match:

php
$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(trim($line));

if (isset($a_line['dirname']) && $a_line['dirname'] === $a_search['dirname']) {
return $index;
}
}


This code will iterate through each line in the $contents array, trim the line to remove any extra whitespace, and compare the 'dirname' part of the filepath with the 'dirname' part of the $searching filepath. If they match, it will return the index of the $contents array.

Make sure to adjust the filepaths and file content according to your actual data.

Rate this post

3 of 5 based on 5778 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us