I know there are similar questions, (this one "How do you use a variable in a regular expression?" seems to be close), but I want to know (the best way) how to fix my problem.
I have some patterns defined which I use to detect an artist and a title in some file names (of MP3 and other audio files). It is similar the way MP3tag (a well known Windows application) converts filenames into MP3 tags. How to do this?
Below a small test application. (Negative cases are missing, but you get the grip.)
<?php
define('SEARCHPATTERNS', array(
'%track%. %artist% - %title%',
'%track% - %artist% - %title%',
'%track%. %title%',
'%track% - %title%',
'%title%'));
define('UNKNOWN_ARTIST_TITLE_ARRAY', array('?', '?'));
$fileNames = array(
'0780. Janis Joplin - Mercedes Benz.mp3',
'0780. Janis Joplin - Mercedes Benz.flac',
'0780 - Janis Joplin - Mercedes Benz.mp3',
'0780 - Janis Joplin - Mercedes Benz.flac',
'0780. Mercedes Benz.mp3',
'0780. Mercedes Benz.flac',
'0780 - Mercedes Benz.mp3',
'0780 - Mercedes Benz.flac',
'Mercedes Benz.mp3',
'Mercedes Benz.flac',
);
//Test some file names
foreach($fileNames as $fileName)
{
$titleAndArtist = GetTitleArtistUsingSearchPattern($fileName);
var_dump($titleAndArtist);
}
function GetTitleArtistUsingSearchPattern($fileName)
{
foreach(SEARCHPATTERNS as $pattern)
{
$artist = '???????????'; // Get it from fileName if it matches the pattern, but how?
$title = '???????????'; // Get it from fileName if it matches the pattern, but how?
if(true) // If is matches.... How?
{
return array(
empty($artist) ? UNKNOWN_ARTIST_TITLE_STRINGS[0] : $artist,
empty($title) ? UNKNOWN_ARTIST_TITLE_STRINGS[1] : $title
);
}
}
return UNKNOWN_ARTIST_TITLE_ARRAY;
}
?>
I am quite sure I have to use a regular expression search (regex) for this. I cannot think clearly right now (thanks to Corona). Help me out please. Very much appreciated!