Hi anyone can help I want separate mp3, mp4 from imploded data in PHP
my data string
$data = "song1.mp3, video1.mp4, song2.mp3"
i want to divide into two separate strings 1 string contains only mp4
with ( ,
) separated and another with mp3
my data from database:
$data = "song1.mp3, video.mp4, song2.mp3";
$mp4 = video1.mp4,video2.mp4,..etc;
$mp3 = song1.mp3,song2.mp3,..etc;
thank you
Assuming your songs names are well formatted, meaning that they are named as title.suffix
<?php
$data = "song1.mp3, video.mp4, song2.mp3";
$mp3 = [];
$mp4 = [];
$song_names = explode(',', $data);
foreach ($song_names as $song_name) {
$song_name = trim($song_name);
$parts = explode('.', $song_name);
if (count($parts) == 2) {
$suffix = $parts[1];
if ($suffix == 'mp3') {
$mp3[] = $song_name;
} else if ($suffix == 'mp4') {
$mp4[] = $song_name;
}
}
}
//using implode so that we won't have an extra comma hanging in the end
$mp4 = implode(', ', $mp4);
$mp3 = implode(', ', $mp3);
?>
Use explode()
to converting string to array by ,
delimiter. Then loop through array items and get extension of file name using substr()
and check it.
$data = "song1.mp3, video1.mp4, song2.mp3";
$mp4 = $mp3 = "";
foreach (explode(",", $data) as $file){
$file = trim($file);
substr($file, -3) == "mp4" ? $mp4.=$file."," : $mp3.=$file.",";
}
$mp4 = substr($mp4, 0, -1);
$mp3 = substr($mp3, 0, -1);
Check result in demo
This sounds like a job for a preg_match_all()
regex:
<?php
$string = 'song1.mp3, video.mp4, song2.mp3';
$regex = '#([^,\s]+\.mp3)#';
preg_match_all($regex, $string, $mp3s);
$regex = '#([^,\s]+\.mp4)#';
preg_match_all($regex, $string, $mp4s);
var_dump($mp3s[0]);
var_dump($mp4s[0]);
Which gives you:
array(2) { [0]=> string(9) "song1.mp3" [1]=> string(9) "song2.mp3" }
array(1) { [0]=> string(9) "video.mp4" }
Here's the code in action https://3v4l.org/2EmkR
Here's the docs for preg_match_all()
http://php.net/manual/en/function.preg-match-all.php
Ok - a slightly different approach using pathinfo
$data = 'song1.mp3, video1.mp4, song2.mp3';
$mp3s = [];
$mp4s = [];
foreach (explode(', ', $data) as $file) {
$type = pathinfo($file)['extension'];
$type === 'mp3' ? $mp3s[] = $file : $mp4s[] = $file;
}
echo implode(', ', $mp4s) . PHP_EOL;
echo implode(', ', $mp3s) . PHP_EOL;
Could definitely use some validation and so forth but as an MVP it does the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.