I'm trying to parse a number of "filename.ext" comming from a file. This exercice comming from CodinGames named "Mime type".
I should take the name of each file, look at his extension, and find the matching key => value in the extensions array.
E.g: for a file named "foobar.pdf", I look if there's a dot, and if it is, I split the name in the files array [foobar => pdf]. If there's no dot like "foobar", it becomes [foobar => Unknown]. Last case asked, if there are two dots, "foo.bar.pdf" is pushing like [foo.bar => pdf] but I'm not here for that case.
My problem is that my first file name is "a" with no dot no extension. So the code runs and does it well. It ends with the perfect input in the files array [a => Unknown]. But now, the second file name is "a.wav". And the program will replace the value of [a => Unknown] to [a => wav] cause it's the same key.
So how can we avoid these replacements ? I searched on web, but everybody are searching to replace key value, not create a new one.
edit: What I expect is have 2 differents input in my file array. In this case I want: $files = [ [a => Unknow], [a => wav], ... ]. After this I must output each mime type comming from the extensions array for each file, so in order: "Uknown", "audio/x-wav", ... this is why I must keep the first key, because there's no extension and it's good to know.
$FNAME = "a
a.wav
b.wav.tmp
test.vmp3
pdf
.pdf
mp3
report..pdf
defaultwav
.mp3.
final.";
There is my code:
$N = 4 // Number of extensions
$Q = 11 // Number of files to parse
$extensions = [
[wav] => audio/x-wav
[mp3] => audio/mpeg
[pdf] => application/pdf
[UNKNOW] => UNKNOWN
];
$files = [];
for ($i = 0; $i < $Q; $i++){
// Input / One file name per line.
$FNAME = stream_get_line(STDIN, 256 + 1, "\n");
// --- TRANSFORM STRING INTO KEY => VALUE ---
// If there is 2 dots e.g "file.name.ext"
if (preg_match('/\..*\./',$FNAME)){
// Do something e.g split string at the second dot, I don't know for the moment how to do this
// I tried regex option U but something wrong happen;
}
// If there is one dot in "filename.ext"
elseif ( preg_match("/\./",$FNAME) ){
$temp = preg_split ("/\./", $FNAME);
// Verification if extension is know
if ( array_key_exists( $temp[1], $extensions) ){
$files[$temp[0]] = $temp[1];
} else {
$files[$temp[0]] = "UNKNOW";
}
} else {
$files[$FNAME] = "UNKNOW";
}
}
a(one withunknown, one with.wav): this won't work